0

Below is a demo illustrating what I mean:

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Canvas Test</title>
</head>
<body>
    <canvas id="canvas" width="800" height="600"></canvas>
    <canvas id="canvas2" width="800" height="600"></canvas>
    <script>
        function randomInteger(min, max) {
            return Math.floor(Math.random() * ((max + 1) - min) + min);
        }
        var start = performance.now();
        var canvas = document.getElementById("canvas");
        var canvas2 = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var ctx2 = canvas2.getContext("2d");
        var points = 1000000; // Changing this changes the performance of drawImage
        for (var i = 0; i < points; i++) {
            ctx.lineTo(randomInteger(0, 800), randomInteger(0, 600));
        }
        ctx.stroke();

        var t0 = performance.now();
        ctx2.drawImage(canvas, 0, 0, 800, 600, 0, 0, 800, 600);
        console.log("Copy time 1: " + (performance.now() - t0) + " ms");

        ctx.lineTo(0, 0);
        ctx.stroke();

        var t1 = performance.now();
        ctx2.drawImage(canvas, 0, 0, 800, 600, 0, 0, 800, 600);
        var end = performance.now();
        console.log("Copy time 2: " + (end - t1) + " ms");
        console.log("Total time: " + (end - start) + " ms");
    </script>
</body>
</html>

On Ubuntu, in Chrome 59 the for 100,000 points the drawImagess take 13ms and 12ms respectively, but for 1,000,000 points the drawImages take 129ms and 706ms respectively. Strangely in Firefox 55 the drawImages happen under 2ms but the total time is comparable to that of Chrome. I assume this is just differences is browser implementations.

I would assume that copying the pixel data from one canvas to another would be a constant time operation (regardless of what is drawn on the source canvas). I assume the discrepancy has something to do with the GPU or memory thrashing due to the volume of points. Is there any insight onto the actual source of this discrepancy and better yet is there a way to improve the performance of drawImage in such as case?

davidMcneil
  • 197
  • 3
  • 11
  • you have to use `drawImage`? – Canet Robern Sep 15 '17 at 01:49
  • For the last question: https://stackoverflow.com/questions/23468218/draw-10-000-objects-on-canvas-javascript (manipulating imagedata is faster than drawImage) – Kaiido Sep 15 '17 at 01:53
  • Why does Chrome take 5 times longer on the second call ? Do not trust the results. To get performance you need a statistical approch as javascript does not execute deterministically. Time the draw calls in batches of 1000+ and do them from timer Events so you let the JS context do its thing. The when you have 1,000,000+ samples and error rate you can ask the Why? On top of that the GPU hardware is the biggest influencing factor of graphics performance. – Blindman67 Sep 15 '17 at 11:05

0 Answers0