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.
Asked
Active
Viewed 4.4k times
14
-
2Are you wanting the canvas to be transparent so that you can place it over other elements? – Justin May 26 '10 at 21:28
-
1No, it's not possible. See this answer: http://stackoverflow.com/questions/2359537/how-to-change-the-opacity-alpha-transparency-of-an-element-in-a-canvas-element – Intelekshual May 26 '10 at 21:42
-
Justin, no I want to draw a semi transparent image on top of other canvas element. I have no interest in making the entire canvas transparent. Intelekshual, setting context.globalAlpha effects subsequent context.drawImages atleast in Chrome. – Mr Bell May 26 '10 at 22:34
3 Answers
23
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.

james.garriss
- 12,959
- 7
- 83
- 96
-
`globalAlpha` will not work for images drawn with `drawImage` in Firefox 30+: https://bugzilla.mozilla.org/show_bug.cgi?id=1028288 – Derek 朕會功夫 Oct 08 '14 at 06:57
-
16
The canvas element has a global alpha attribute that lets you apply partial transparency to anything you draw.

Undo
- 25,519
- 37
- 106
- 129

Eric Mickelsen
- 10,309
- 2
- 30
- 41
-
-
Link is broken. See http://dev.w3.org/html5/2dcontext/#dom-context-2d-globalalpha – Meekohi Feb 22 '12 at 22:42
4
It's possible if you iterate thru the canvas' image-data and set the alpha value manually, then export the transparent image with the canvas.toDataURL method and insert it into another canvas.

Matt
- 74,352
- 26
- 153
- 180

Patrick Wied
- 61
- 2
-
You don't have to call toDataURL if you want to draw a canvas on an other, `drawImage` accepts canvas as imageSource. – Kaiido Jul 09 '16 at 23:27