javascripthtmlcanvasdouble-buffering

Does HTML5/Canvas Support Double Buffering?


What I'd like to do is draw my graphics on a buffer and then be able to copy it as is to the canvas so I can do animation and avoid flickering. But I couldn't find this option. Anyone know how I can go about this?


Solution

  • The following helpful link, in addition to showing examples and advantages of using double buffering, shows several other performance tips for using the html5 canvas element. It includes links to jsPerf tests, which aggregate test results across browsers into a Browserscope database. This ensures that the performance tips are verified.

    https://web.dev/canvas-performance/

    For your convenience, I have included a minimal example of effective double buffering as described in the article.

    // canvas element in DOM
    var canvas1 = document.getElementById('canvas1');
    var context1 = canvas1.getContext('2d');
    
    // buffer canvas
    var canvas2 = document.createElement('canvas');
    canvas2.width = 150;
    canvas2.height = 150;
    var context2 = canvas2.getContext('2d');
    
    // create something on the canvas
    context2.beginPath();
    context2.moveTo(10,10);
    context2.lineTo(10,30);
    context2.stroke();
    
    //render the buffered canvas onto the original canvas element
    context1.drawImage(canvas2, 0, 0);