How to change the opacity (alpha, transparency) of an element in a canvas element?

Using the HTML5 <canvas> element, I would like to load an image file (PNG, JPEG, etc.), draw it to the canvas completely transparently, and then fade it in. I have figured out how to load the image and draw it to the canvas, but I don’t know how to change its opacity.

Here’s the code I have so far:

var canvas = document.getElementById('myCanvas');
    
if (canvas.getContext)
{
    var c           = canvas.getContext('2d');
    c.globalAlpha   = 0;
    
    var img     = new Image();
    img.onload  = function() {
        c.drawImage(img, 0, 0);
    }
    img.src="https://stackoverflow.com/questions/2359537/image.jpg";
}

Will somebody please point me in the right direction like a property to set or a function to call that will change the opacity?

9 Answers
9

Leave a Comment