serious-scribbler
serious-scribbler

Reputation: 31

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

Upvotes: 3

Views: 3206

Answers (2)

E. Charette
E. Charette

Reputation: 66

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.

Upvotes: 3

markE
markE

Reputation: 105015

There are several possible issues with your code:

  • The image might not really be transparent.
  • The image might not be fully loaded when you try to draw it. Use img.onload to wait until the img is fully loaded before trying to draw it.
  • When you createElement('canvas') the default size of the canvas is 300x150 so your image is probably larger or smaller than the default canvas size. Use canvas.width=img.width & canvas.height=img.height to set the canvas size to the img size.
  • If the image URL is from a different domain than the web page then a security error will be raised. This error condition will prevent .getImageData from returning data.

Here's your code refactored to avoid those issues:

var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/icon_64x64.png";
function start(){

    var canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    canvas.width=img.width;
    canvas.height=img.height;
    var context = canvas.getContext('2d');
    context.drawImage(img, 0, 0);
    var data = context.getImageData(0, 0, img.width, img.height).data;
    var alphas=''; // demo purposes
    for(var i = 0; i<data.length; i+=4){
        console.log(data[i+3]);
        if(i<200){alphas+=data[i+3]+',';} // demo purposes
    }

    alert(alphas); // demo purposes
}
body{ background-color: ivory; }
canvas{border:1px solid red; margin:0 auto; }

Upvotes: 1

Related Questions