canvas-clear

JavaScript performance comparison

Revision 9 of this test case created by Prestaul

Info

Different methods for clearing the canvas.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var c = document.createElement('canvas');
    c.width = c.height = 500;
   
    var ctx = c.getContext('2d');
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, 500, 500);
   
};

Benchmark.prototype.teardown = function() {
    var p = ctx.getImageData(0, 0, 1, 1);
    if (p.data[3] != 0) throw ("canvas did not clear!");
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
clearRect
ctx.clearRect(0, 0, c.width, c.height);
 
pending…
fillRect
ctx.save();
ctx.globalCompositeOperation = 'copy';
ctx.fillStyle = 'rgba(0,0,0,0)';
ctx.fillRect(0, 0, c.width, c.height);
ctx.restore();
pending…
set width
c.width = 0;
c.width = c.width;
pending…
clear transform then clearRect
// Store the current transformation matrix
ctx.save();

// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, c.width, c.height);

// Restore the transform
ctx.restore();
 
pending…
putImageData
var data = ctx.createImageData(c.width, c.height);
ctx.putImageData(data, 0, 0); // clear context by putting empty image data
 
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment