canvasdata-urigetimagedataoff-screenputimagedata

Most efficient way to reuse an HTML5 canvas's drawn content


I use an offscreen canvas to dynamically generate certain images based on the runtime value of certain variables. Once the image has been drawn on the offscreen canvas, I want to get it and use it in several places of my webapp.

Strategy 1: use the offscreen canvas's toDataURL() method to obtain a data: URI that contains the image, and which I can programmatically set on the multiple img elements in the page that are supposed to display it.

Strategy 2: use the offscreen canvas's getImageData() method to obtain an ImageData instance. Replace the img elements with canvas elements and call putImageData() on them.

Which strategy is more efficient memory wise? Which is more “idiomatic”? I'm trying to avoid duplicating the memory needed to hold the instances of the displayed images. Other suggestions?


Solution

  • Use canvas elements instead of img elements.

    Then draw the in-memory canvas to the onscreen canvases. A canvas element can use another canvas as a drawImage source:

    context.drawImage(inMemoryCanvasElementReference,0,0);
    

    BTW, the imageData commands (.getImageData and .putImageData) are very memory inefficient because they build an entire new array of pixel data. They also lack performance because they are not GPU accelerated.