Why is putImageData so slow?

后端 未结 4 777
梦谈多话
梦谈多话 2020-11-30 20:07

I am working with a relatively large Canvas where various (complex) stuff is drawn to. I then want to save the Canvas\' state, so I can quickly reset it to the state it now

4条回答
  •  生来不讨喜
    2020-11-30 21:04

    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), 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 arbitary 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.

提交回复
热议问题