Why is putImageData so slow?

Just a small update on what the best way is to do this. I actually wrote my Bachelor Thesis on High Performance ECMAScript and HTML5 Canvas (pdf, German; password: stackoverflow), so I gathered some expertise on this topic by now. The clearly best solution is to use multiple canvas elements. Drawing from one canvas onto another canvas is just as fast as drawing an arbitrary image to a canvas. Thus “storing” the state of a canvas is just as fast as restoring it later again when using two canvas elements.

This jsPerf testcase shows the various approaches and their benefits and drawbacks very clearly.

Just for completeness, here how you really should do it:

// setup
var buffer = document.createElement('canvas');
buffer.width = canvas.width;
buffer.height = canvas.height;


// save
buffer.getContext('2d').drawImage(canvas, 0, 0);

// restore
canvas.getContext('2d').drawImage(buffer, 0, 0);

This solution is, depending on browser, up to 5000x faster than the one getting the upvotes.

Leave a Comment