1

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 !

Thank's

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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...
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))
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.
All canvases have an alpha channel. In fact the default canvas is transparent black (aka rgba(0,0,0,0))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.