Take the 2-minute tour ×

I'd like to know if it possible to not use the alpha channel but keeping transparency. What I need is to draw or not draw pixel (of my png file) depending on the alpha value

If alpha channel > 128 draw Pixel else don't draw pixel !


share|improve this question

1 Answer 1

up vote 0 down vote accepted

There are probably a few ways to go about that.

One way is just to draw the image, then call getImageData

Go over every pixel in the image data, and if the alpha component is <= 128, make that pixel fully transparent.

Then put the modified imageData back with putImageData

This is from memory so I might have missed something:

var imageData = ctx.getImageData(0,0,picwidth, picheight);
var pixels = imageData.data;
var numPixels = pixels.length;

ctx.clearRect(0, 0, can.width, can.height);

for (var i = 0; i < numPixels; i++) {
    if (pixels[i*4+3] <= 128) pixels[i*4+3] = 0;
ctx.putImageData(imageData, 0, 0);
share|improve this answer
i'll try thank you –  webshaker Aug 16 '11 at 16:06
well, in fact this is not what i'm looking for. A'd like to modify the image and not the canvas. I want to make a pre traitment before blitting the image... –  webshaker Aug 17 '11 at 14:45
So you must do the exact same thing as above, except draw the image to an in-memory canvas. So use document.createElement('canvas') to make a new canvas, draw the image to it, apply the above operations, and then draw that canvas to your normal canvas. (ctx.drawImage(tempCanvas, 0, 0)) –  Simon Sarris Aug 17 '11 at 15:50
ah ok. thank's. I'll try. but that mean that a canvas can have a alpha channel. I'll try... That will be great if it's work. –  webshaker Aug 17 '11 at 16:33
All canvases have an alpha channel. In fact the default canvas is transparent black (aka rgba(0,0,0,0)) –  Simon Sarris Aug 18 '11 at 13:40

Your Answer


