2

In JavaScript I can directly manipulate the pixels of a canvas and refresh them with a single copy:

ctx = canvas.getContext('2d')
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
pixelTypedArray = imageData.data

modifyPixels(pixelTypedArray)

// refresh canvas with single copy
ctx.putImageData(imageData, 0, 0)

But in wasm we must allocate our own TypedArray using the wasm memory, and we can then use imageData.data.set(myTypedArray) but that seems to just copy the entire contents of the new typed array into the canvas's typed array, which must still be followed by putImageData, copying the entire contents a second time.

Is there any way to reassign the canvas's ImageData to our new ImageData so that we can update the canvas with only a single copy using ctx.putImageData()?

If not, it seems much of the benefit of using wasm to manipulate the image would be wasted by the inefficient double copy and dual in-memory representation, especially when working with large images and/or continuously updating canvas.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
  • 1
    The ImageData you got is completely detached from the canvas, so calling it "the canvas's ImageData" is a bit misleading. I'm not into wasm and so I'm not too sure as to how you sahre memory between assemblyscripts and js. Can you *tranfer* it? Is your `myTypedArray` always the same object? You can very well create a new ImageData from an ArrayBuffer quite easily, without the need to `set` anything. So if you can [transfer this ArrayBuffer](https://stackoverflow.com/questions/41722068/41732553#41732553), then you can have a single copy (and the internal one(s) of the canvas) – Kaiido Oct 14 '19 at 12:00
  • @Kaiido: Thanks! While the transferring was new to me and doesn't seem to be supported by wasm, what I needed was to create my own ImageData as well as my own TypedArray. I had tried each separately but not both together. (The only vaguely similar examples I could find while teaching myself this stuff were also double-copying.) If you post an answer I will accept it. – hippietrail Oct 14 '19 at 13:03

0 Answers0