Question

i have this script.

var oriToCopy = function(){
    while(pps.length > 0){
        var pp = pps.pop();
        layerDataCopy.data[pp] = layerDataOri.data[pp];
        layerDataCopy.data[pp + 1] = layerDataOri.data[pp + 1];
        layerDataCopy.data[pp + 2] = layerDataOri.data[pp + 2];
    }
    ctxCopy.putImageData(layerDataCopy, 0, 0);
}

where : pps is array of pixel position in the canvas
layerDataOri is imageData from Original canvas
layerDataCopy is imageData from Copy canvas

what i am trying to do is to copy layerDataOri at layerDataOri.data[pps] to layerDataCopy.data[pps]. i have check that pixel at pps position is not a transparent pixel, but when copy this pixel to layerDataCopy it's not affected, the copy canvas is still transparent.

what is wrong?

Was it helpful?

Solution

Make sure you also copy the alpha channel as each pixels consist of four channels (RGBA):

layerDataCopy.data[pp] = layerDataOri.data[pp];
layerDataCopy.data[pp + 1] = layerDataOri.data[pp + 1];
layerDataCopy.data[pp + 2] = layerDataOri.data[pp + 2];
layerDataCopy.data[pp + 3] = layerDataOri.data[pp + 3]; // alpha

Note that pp must also be quantized by 4 to point to a valid pixel (you're now showing how you generate the positions in the question, so just in case).

If the canvas you're getting the copy buffer from is blank (nothing drawn into it) all pixels will be transparent by default. So when, during the copy, the alpha channel isn't copied over the pixel will remain transparent.

You could also use createImageData instead of getImageData for the copy buffer if it isn't containing any data in advance (it's faster).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top