Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw transparent image with html5 canvas element

I am targeting google chrome. Is it possible to draw transparent images on a canvas? By transparent I mean the drawing the entire image at something like 50% opacity.

like image 839
Mr Bell Avatar asked May 26 '10 21:05

Mr Bell


People also ask

How do I make a picture transparent in canvas?

With Canva Pro, simply choose PNG, then click the box with the transparent background option.

How do you make a transparent canvas in HTML?

Learn HTML The globalAlpha property returns the transparency value of drawing. The value 1.0 of this property specifies no transparency and the value 0.0 of this property specifies full transparency. Hence, by setting the globalAlpha property to 0.0, we can get a transparent canvas.

Can HTML canvas be transparent?

Canvases are transparent by default. Try setting a page background image, and then put a canvas over it. If nothing is drawn on the canvas, you can fully see the page background.


1 Answers

You can do this using the globalAlpha property, like this:

<!DOCTYPE HTML>
<html>
    <body>
        <canvas height="100" width="100" id="myCanvas"></canvas>
        <script>
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.globalAlpha = 0.5;
            var myImage = new Image();
            myImage.src = "someImage.jpg";
            myImage.onload = function()
            {
                context.drawImage(myImage, 0, 0, 100, 100);
            };
        </script>
    </body>
</html>

And yes, it does work with images. Verified with IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.

like image 189
james.garriss Avatar answered Sep 21 '22 15:09

james.garriss