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 drawImages
s take 13ms and 12ms respectively, but for 1,000,000 points the drawImage
s take 129ms and 706ms respectively. Strangely in Firefox 55 the drawImage
s 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?