1

I'm in the process of trying to optimize a game consisting of a HTML5 canvas. The basic game idea is to take an ImageData object (presumably with getImageData) and modify it, replacing the original (presumably with putImageData). Problem is I'm concerned with the performance of getImageData followed by putImageData as the process of transferring to and from a canvas object is quite cumbersome when ideally one could just write to it directly instead. Essentiallt hoping to display a Uint8Array **while** also reading said array for the next iteration.

This is me postulating but considering how I'm *just* taking ImageData from a canvas object and using it to modify another I fail to see the need for any data to be copied as a whole ever. The data could be read from one `ImageData´, written to another after which the canvas image reference could be switched with both objects being allocated from the very beginning.

I guess what I'm after is some sort of double buffering? The idea is to modify a dataset, display it, and then use that same dataset on display for the next iteration avoiding unnecessary copying in between.

s1gtrap
  • 162
  • 2
  • 10
  • From your description you can indeed remove entirely the `getImageData` step, keep only one ImageData object, created either woth the new ImageData(w, h) constructor or ctx.createImageBitmap work on that and putImageData it on the canvas context every frame. And the good thing is that getImageData os really the slow one. – Kaiido Apr 18 '22 at 23:26
  • @Kaiido so in essence as `putImageData` is cheap, you could easily iterate one `ImageData` to another and then simply swap the two? – s1gtrap Apr 19 '22 at 21:01
  • putImageData does copy the ImageData to the canvas buffer, you don't swap anything. So you keep one and only one ImageData on your side and you copy it to the canvas every frame. – Kaiido Apr 19 '22 at 22:33
  • @Kaiido that's what I was worried about though. I need to read from the current buffer in order to prepare the next, so it would make perfect sense to have one `ImageData` to display and another to update and then just swap the two when ready, but if `putImageData` copies that sort of defeats the purpose. It would work much better if an explicit double buffering/'swap these two `ImageData`' was available. – s1gtrap Apr 20 '22 at 07:40
  • There isn't. The only way to write data on the canvas buffer is to copy it. But that's still magnitudes better to keep your own ImageData all the way and only put it on the context buffer every frame than reading it from the context like you were considering. No new memory is allocated in the process. – Kaiido Apr 20 '22 at 07:45

0 Answers0