HTML5 how to draw a transparent pixel image in canvas

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

+5
source share
3 answers

If I understand what you need, you basically want to turn certain colors into transparent images. For this you need to use getImageDatato find out how to manipulate mdn pixels .

Here is a 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 code above you can check fuschia using

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

+7
source

I think you need the canvas clearRect method:

http://www.w3schools.com/html5/canvas_clearrect.asp

( RGBA) .

+2

0 , , - 255 , , .

( 0), , RGB, 0. , , , . - 0, RGB.

Alpha 127 , , 50% .

, , , .

0
source

All Articles