Fastest way to iterate pixels in a canvas and copy some of them in another one

馋奶兔 提交于 2019-12-04 11:01:25

Don't set your image data in every iteration of the loop. That's a heavy operation, and you're executing it 40.000 (200*200) times.
This should save you a bit of processing power:

var contexts = [];
var data = [];
// Save your contexts and data to 2 arrays.
for (var i = 0; i < layers.length; i++) {
    contexts[i] = layers[i].getContext("2d");
    data[i] = contexts[i].getImageData(0, 0, totalWidth, totalHeight);
}

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);

        data[layerIndex].data[index] = originalData[index];
        data[layerIndex].data[index + 1] = originalData[index + 1];
        data[layerIndex].data[index + 2] = originalData[index + 2];
        data[layerIndex].data[index + 3] = originalData[index + 3];
    }
}

// Apply your new data to the contexts.
for (var i = 0; i < layers.length; i++) { 
    contexts[i].putImageData(data[i]);
}

I haven't tested it, but this should give you a bit of an idea of how to do it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!