views:

1842

answers:

3

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 once it as been drawn.

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     = '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? Thanks!

+3  A: 

You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.

If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.

MPG
+2  A: 

I am also looking for an answer to this question, (to clarify, i want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as i have concluded right now, this does not seem to affect image drawing.

//works with shapes but not with images
canvas2d.fillStyle = "rgba(255, 255, 255, 0.5)";

I have concluded that setting the globalCompositeOperation works with images.

//works with images
canvas2d.globalCompositeOperation = "lighter";

I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.

EDIT:

After further digging i have concluded that you can set the transparency of an image by setting the globalAlpha parameter before you draw the image:

//works with images
canvas2d.globalAlpha = 0.5

If you want to acheive a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to acheive it is the setTimeout function, look that up to create a loop from wich you alter the alpha over time.

djdolber
A: 

You can use "opacity" CSS property. Load up the image and animate that. It should do the trick.

bebraw