Why is setting HTML5's CanvasPixelArray values is ridiculously slow and how can I do it faster?

Posted by Nixuz on Stack Overflow See other posts from Stack Overflow or by Nixuz
Published on 2010-04-04T01:05:08Z Indexed on 2010/04/04 1:13 UTC
Read the original article Hit count: 319

I am trying to do some dynamic visual effects using the HTML 5 canvas' pixel manipulation, but I am running into a problem where setting pixels in the CanvasPixelArray is ridiculously slow.

For example if I have code like:

imageData = ctx.getImageData(0, 0, 500, 500);

for (var i = 0; i < imageData.length; i += 4){
    imageData.data[index] = buffer[i];
    imageData.data[index + 1] = buffer[i];
    imageData.data[index + 2] = buffer[i];
}

ctx.putImageData(imageData, 0, 0);

Profiling with Chrome reveals, it runs 44% slower than the following code where CanvasPixelArray is not used.

tempArray = new Array(500 * 500 * 4);
imageData = ctx.getImageData(0, 0, 500, 500);

for (var i = 0; i < imageData.length; i += 4){
    tempArray[index] = buffer[i];
    tempArray[index + 1] = buffer[i];
    tempArray[index + 2] = buffer[i];
}

ctx.putImageData(imageData, 0, 0);

My guess is that the reason for this slowdown is due to the conversion between the Javascript doubles and the internal unsigned 8bit integers, used by the CanvasPixelArray.

  1. Is this guess correct?
  2. Is there anyway to reduce the time spent setting values in the CanvasPixelArray?

© Stack Overflow or respective owner

Related posts about canvaspixelarray

Related posts about html5