JavaScript to automatically make an image be transparent

make the image that is displayed on a canvas context, be transparent:

assumptions:
- the image is already displayed in the given canvas context
- the first pixel at the top left is the color that you want to be made transparent
- the pixels are an exact match (the code does not try to make a fuzzy match like Photoshop would)

var makeImageTransparent: function(ctx, width, height) {
      // get the image data object
    var image = ctx.getImageData(0, 0, width, height);
    // get the image data values 
    var imageData = image.data,
    length = imageData.length;
 
    //set the data, where we find a match to top-left pixel's RGB values:
    for (var i = 3; i < length; i += 4) {
        if(imageData[i+1] === imageData[3+1] &&
            imageData[i+2] === imageData[3+2] &&
            imageData[+ 3] === imageData[3 + 3]) {
            //set the alpha channel:
            imageData[i] = 0;
        }
    }
    // after the manipulation, store the data
    image.data = imageData;
    // and put the imagedata back to the context
    ctx.putImageData(image, 0, 0);
  };

// usage:
makeImageTransparent(context, width, height);


based on code from this site (which did not quite work for me, so hence this post)
http://www.patrick-wied.at/blog/how-to-create-transparency-in-images-with-html5canvas

Comments