The <canvas>
can be quite useful, especially if you want to modify how images look on your site. For example, if you want to make an image appear as a gradient starting at the top with an alpha of 0
and then linearly fading to the image’s full alpha value you can use JavaScript along with the <canvas>
:
-
Make Sure The Image Is On Your Domain
If the image that you are trying to modify is not on your site’s domain you will not be able to modify it using the canvas unless the image is CORS enabled or unless you are pulling the image via an<input type="file">
. -
Create the Canvas & Add the Image To It
var image = document.getElementById('id_of_image'); var canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; var context = canvas.getContext('2d'); context.drawImage(image, 0, 0);
-
Retrieve & Modify Alpha Values
The canvas’ 2D context object provides a function calledgetImageData()
which will return another object. This object’sdata
property is an array of the rgba values that make up the image. In other words, the first four values in the array represent the top-most and left-most pixel in the image while the second four values represent the next pixel going from left-to-right and top-to-bottom. Since we want to create a fading gradient effect we need to determine they
value at all times to then figure out thealpha
which will depend on themaxY
value. NOTE: the alpha value ranges from 0 to 255.var imageData = context.getImageData(0, 0, image.width, image.height); var d = imageData.data; var maxY = image.height; for (var y, alpha, i = 3, l = d.length; i < l; i += 4) { y = Math.floor(i / 4 / image.width); alpha = Math.round(255 * y / maxY); d[i] = Math.min(d[i], alpha); }
-
Reset Canvas & Set Updated Image Data
Since we have played around with the alpha values we don’t want to simply draw the image data on top of the canvas. Instead we need to clear that canvas and then draw the updated image:context.clearRect(0, 0, image.width, image.height); context.putImageData(imageData, 0, 0);
-
Use Canvas Data URL As Image’s Source
The canvas has a handy function calledtoDataURL()
which among other things can be used to pull a PNG version of our image which will preserve the transparency. All we need to do is assign this data URL to image’ssrc
property and then we are done:image.src = canvas.toDataURL();
-
Try It Out
Feel free to try this code out on your site or you can see how it all works together by using the button below to choose an image to convert to a gradient. After the image is created you should be able to click on it to open it up in a new tab.