Search code examples
canvasdirty-dataimagedata

How to use imageData in animations


I have an object that stores imageData with a createImageData() function. I do not want to create any more imageDatas, but I want the data to be cleared each frame. How do I do this?


Solution

  • You can call its .data Uint8ClampedArray's fill(0) method, this will reset all the pixels to transparent black.

    For better perfs, you can even create an Uint32Array view over this .data's ArrayBuffer:

    const canvas = document.getElementById( 'canvas' );
    const ctx = canvas.getContext( '2d' );
    const imgData = ctx.createImageData( 500, 500 );
    for(let i=0; i<imgData.data.length*4; i++) {
      imgData.data[ i ] = Math.random() * 255; // some noise
    }
    ctx.putImageData( imgData, 0, 0 );
    ctx.font = "30px sans-serif";
    ctx.fillText( "click to clear", 30, 30 );
    canvas.onclick = (evt) => {
      // clear the ImageData
      new Uint32Array( imgData.data.buffer ).fill(0);
      ctx.putImageData( imgData, 0, 0 );
    
    };
    <canvas id="canvas" width="500" height="500" ></canvas>