iedoc
iedoc

Reputation: 2324

keep reference to javascript canvas imageData

Is it possible to keep a reference to the actual imageData rather than calling getImageData every frame?

The problem is that i'm getting fps drops in consistent intervals when calling getImageData on the canvas context which i need to read the actual data.

When the page loads, i first create an array that is large enough to hold the imageData.data, so that memory is not being allocated every frame. To update that array, i have to call getImageData on the canvas context. If i run the javascript like this, every couple seconds there is a drop in fps from around 60 to 20-30.

When i comment out the line that calls getImageData, the script runs smoothly at around 60fps

for example, this code will cause a drop in fps

// initialize m_canvasData
var m_canvasData = m_canvasContext.getImageData(0, 0, m_width, m_height).data;

// called every frame
function loop()
{
    m_canvasData = m_canvasContext.getImageData(0, 0, m_width, m_height).data;
}

this code will not cause a drop in fps

var m_canvasData = m_canvasContext.getImageData(0, 0, m_width, m_height).data;

// called every frame
function loop()
{
   // m_canvasData = m_canvasContext.getImageData(0, 0, m_width, m_height).data;
}

I would like to just keep a reference to the canvas data rather than calling getImageData every frame if thats possible.

I'm not an expert but i do know the DOM comes into place somewhere, so if it is not possible to hold a reference to the address of the canvas data, what is the most efficent way to get the data?

Three.js is somehow able to get 60fps when i give it a canvas to use as a texture, so i know there is some way around getting a drop in fps when getting canvas data

There is only one thread in the code, so i do not believe it should be a multi threaded issue where the getImageData has to wait for another javascript thread (although maybe its waiting for the browser to finish drawing the canvas? but the browser is refreshing at 60-61 fps, so i don't think thats the issue either)

Upvotes: 0

Views: 384

Answers (1)

markE
markE

Reputation: 105015

It makes sense that your FPS is dropping if you call .getImageData constantly because it involves duplicating and transferring a large amount of memory. Also, .getImageData does not use the GPU so the processing burden is passed onto your probably-busy CPU.

No ... you can't keep a "live" reference to canvas's image data.

var idata=context.getImageData(0,0,canvas.width,canvas.height);

...returns a static "snapshot" of the pixels of the current canvas content. If you draw something new on the canvas, then idata will not contain the new drawing.

Your question does not contain enough info to help with more detail, but the common workaround is to refactor your app to not use .getImageData.

Upvotes: 1

Related Questions