I'm into a 2D/3D graphic project and I'm facing a performance problem.
My algorithm takes two images: a picture and the relative grayscale depth map. I have also an array of 10 canvases ("layers") initally blank. A note: all the images have the same dimension.
I need to check every pixel X;Y of the depth map and, depending on its color value, access one of the 10 canvases and draw the X;Y pixel of the original image on it.
Resulting algorithm is someting like:
for (var y = 0; y < totalHeight; ++y) {
for (var x = 0; x < totalWidth; ++x) {
var index = (y * totalWidth + x) * 4; // index of the current pixel
// parse depth level using luminosity method
var depthLevel = Math.round(
0.21 * depthData[index] +
0.71 * depthData[index + 1] +
0.07 * depthData[index + 2]
);
// get the proper layer to modify
var layerIndex = Math.floor((layersCount / 256) * depthLevel);
var layerContext = layers[layerIndex].getContext("2d");
var layerData = layerContext.getImageData(0, 0, totalWidth, totalHeight);
layerData.data[index] = originalData[index];
layerData.data[index + 1] = originalData[index + 1];
layerData.data[index + 2] = originalData[index + 2];
layerData.data[index + 3] = originalData[index + 3];
layerContext.putImageData(layerData, 0, 0);
}
A loop like that takes around 3 minutes to complete on a 200x200 image! I'm pretty sure that the slowness is caused by the last function, putImageData. Is there a faster way to draw pixels in the way I need? Thank you