HTML5 how to draw transparent pixel image in canvas

canvas, html, image, pixel, transparent

Solution

If I understand what you need, you basically want to turn specific colors on an image transparent. To do that you need to use `getImageData` check out mdn for an explanation on pixel manipulation.

Heres some sample code

var imgd = ctx.getImageData(0, 0, imageWidth, imageHeight),
    pix = imgd.data;

for (var i = 0, n = pix.length; i <n; i += 4) {
    var r = pix[i],
        g = pix[i+1],
        b = pix[i+2];

    if(g > 150){ 
        // If the green component value is higher than 150
        // make the pixel transparent because i+3 is the alpha component
        // values 0-255 work, 255 is solid
        pix[i + 3] = 0;
    }
}

ctx.putImageData(imgd, 0, 0);​

And a working demo

With the above code you could check for fuschia by using

`if(r == 255 && g == 0 && b == 255)`

Problem

I'm drawing an image using rgb pixel data. I need to set transparent background color for that image. What value I can set for alpha to be a transparent image? Or is there any other solution for this?

Original source

Related problems