Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 how to draw transparent pixel image in canvas

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?

like image 924
Joe Avatar asked Apr 04 '12 20:04

Joe


People also ask

Can HTML canvas be transparent?

Complete HTML/CSS Course 2022 The globalAlpha property returns the transparency value of drawing. The value 1.0 of this property specifies no transparency and the value 0.0 of this property specifies full transparency. Hence, by setting the globalAlpha property to 0.0, we can get a transparent canvas.

How do I change transparency in canvas?

In the Canvas Layer Editor window (Windows > Editors > Canvas Layer Editor ), click on the image layer's and drag up (higher opacity) or down (lower opacity).


2 Answers

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)

like image 178
Loktar Avatar answered Oct 31 '22 16:10

Loktar


I think you want the clearRect canvas method:

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

This will let you clear pixels to transparent (or any other RGBA color) without fuss or pixel manipulation.

like image 2
Colin Godsey Avatar answered Oct 31 '22 16:10

Colin Godsey