How to create transparency in images with canvas
This article is about how to create transparency in all types of images ( .JPEG, .GIF, .PNG ) with only the html5 canvas element and some javascript. I wrote this article because I’ve recently released watermark.js which exactly does that for your images. Your first guess about how this works might be “hey, lets set globalAlpha to a value of my choice then draw my image into the canvas and it will work”. Unfortunately that’s not a solution for this problem, the context’s globalAlpha attribute only works for drawing shapes and lines, but here is a step by step guide how it works on any image:
1. Add your image into the canvas element
2. Loop thru the image and set px by px the alpha value of your choice
3. Get the canvas’ dataURL, tada
Doesn’t look too hard, does it? Let’s have a look at a possible implementation! :)
Step 1: kids stuff
First we have to create a canvas element, add it to the document’s body, set the canvas size to the image size (we have a 500×200 img) and add the image to the canvas.
// get the image var img = document.getElementById("your-image"); // create and customize the canvas var canvas = document.createElement("canvas"); canvas.width = 500; canvas.height = 200; document.body.appendChild(canvas); // get the context var ctx = canvas.getContext("2d"); // draw the image into the canvas ctx.drawImage(img, 0, 0);
Step 2: the interesting part
Ok this is the more interesting part of the solution. We have to access the image data, loop thru all pixels of the image and set the alpha values to the value of our choice. A pixel in the imagedata is represented by four values: red, green, blue, alpha (rgba) therefore we have to change every fourth value.
// get the image data object var image = ctx.getImageData(0, 0, 500, 200); // get the image data values var imageData = image.data, length = imageData.length; // set every fourth value to 50 for(var i=3; i < length; i+=4){ imageData[i] = 50; } // after the manipulation, reset the data image.data = imageData; // and put the imagedata back to the canvas ctx.putImageData(image, 0, 0);
The alpha value could be 0 to 255 just like the r,g,b values. 0 <= alpha <= 255, therefore if you like to set a percentage you have to calculate (255/ (100/percentage value))
Step 3: the relief
Finally you can access the new image data with the toDataURL function and set it to the image
img.src = canvas.toDataURL();
Keep in mind the default data url image type is .PNG, therefore you can have transparency :) If you set another image type in the dataURL (such as “image/jpg”) the transparency is lost.
Hope you enjoyed the article. Cheers, Patrick