Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - getImageData on canvas always returns alpha 255

I am trying to read the alpha values in an image with javascript and canvas, but the alpha part of the ImageData returned by getImageData is always 255 even if the processed image only consists of transparent pixels. This is what i did:

var img = new Image();
img.src = "url/to/an/image/with/transparency";
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var data = context.getImageData(0, 0, img.width, img.height).data;
for(var i = 0; i<data.length; i+=4){
    console.log(data[i+3]);
}

This always outputs 255. I already found this, but it didn't really help me: newbie keeps losing alpha values in canvas

No matter what i try, it wont work.

EDIT: This is my full code: http://pastebin.com/3giQCWvP

The mistakes occur inside the generateCollisionGrid() function. I found out that red and green are also always 255.

This is the image i used for testing: https://addons.opera.com/media/extensions/03/1303/1.4-rev1/icons/icon_64x64.png

like image 759
serious-scribbler Avatar asked Apr 30 '26 11:04

serious-scribbler


1 Answers

I had the same issue and found that I needed to set the context.globalCompositeOperation = "copy" to ensure that the alpha overrode the destination data.

like image 92
E. Charette Avatar answered May 02 '26 01:05

E. Charette