Question

window.onload = function() {
                var Can1 = document.getElementById('canvas2');

                    var ctx = Can1.getContext("2d");
                    Can1.width=960;
                    Can1.height=720;
                        //ctx.fillStyle = "rgba(0,255,0,0)";
                        //ctx.fillRect(0,0,960,720);
                    var imgData=ctx.getImageData(0,0,960,720);
                     for (var i=0;i<imgData.data.length;i+=4)
                          {
                             imgData.data[i]=255/*-imgData.data[i]*/;
                             imgData.data[i+1]=0/*255-imgData.data[i+1]*/;
                             imgData.data[i+2]=0/*255-imgData.data[i+2]*/;
                             imgData.data[i+3]=255-imgData.data[i+3];
                          }
                          ctx.putImageData(imgData,0,0);




}
Was it helpful?

Solution

This will change every pixel of your canvas to red with alpha unchanged;

    var Can1 = document.getElementById("canvas2");
    var ctx = Can1.getContext("2d");

    // get all canvas pixel data
    imgData = ctx.getImageData(0, 0, Can1.width, Can1.height);

    // change every pixel on the canvas to rgba(255,0,0,255);
    for (var i=0;i<imgData.data.length;i+=4){
        imgData.data[i]=255     // this is the red component of this pixel
        imgData.data[i+1]=0     // this is the green component of this pixel
        imgData.data[i+2]=0     // this is the blue component of this pixel
        // To keep the alpha the same, just leave .data[i+3] unchanged
        //imgData.data[i+3];  // this is the alpha component of this pixel
    }

    // replace all the canvas pixels with your modified pixels
    ctx.putImageData(imgData,0,0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top