img vs canvas performance test
by Gustavo Carvalho
HTML
<canvas id="canvas" width=500 height=300 />
JavaScript
(function () {
// main canvas
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// offscreen canvas
var spriteCanvas = document.createElement("canvas");
spriteCanvas.width = 500;
spriteCanvas.height = 300;
var spriteCtx = spriteCanvas.getContext("2d");
spriteCtx.beginPath();
// redraw the cloud
spriteCtx.moveTo(170, 80);
spriteCtx.bezierCurveTo(130, 100, 130, 150, 230, 150);
spriteCtx.bezierCurveTo(250, 180, 320, 180, 340, 150);
spriteCtx.bezierCurveTo(420, 150, 420, 120, 390, 100);
spriteCtx.bezierCurveTo(430, 40, 370, 30, 340, 50);
spriteCtx.bezierCurveTo(320, 5, 250, 20, 250, 50);
spriteCtx.bezierCurveTo(200, 5, 150, 20, 170, 80);
// complete custom shape
spriteCtx.closePath();
spriteCtx.lineWidth = 5;
spriteCtx.strokeStyle = 'blue';
spriteCtx.fillStyle = 'grey';
spriteCtx.stroke();
spriteCtx.fill();
var url = spriteCanvas.toDataURL();
var img = new Image();
img.src = url;
var initial = Date.now();
for (var i = 0; i<30000; ++i){
context.drawImage(spriteCanvas, 0, 0);
}
var total = Date.now() - initial;
console.log("canvas:"+(total/1000)+" seconds");
initial = Date.now();
for (var i = 0; i<30000; ++i){
context.drawImage(img, 0, 0);
}
total = Date.now() - initial;
console.log("image: "+(total/1000)+" seconds");
})();