Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing PNG to a canvas element -- not showing transparency

I'm trying to use drawImage to draw a semi-transparent PNG on a canvas element. However, it draws the image as completely opaque. When I look at the resource that's being loaded and load the actual PNG in the browser, it shows the transparency, but when I draw it on the canvas, it does not. Any ideas?

Here's the code:

drawing = new Image()  drawing.src = "draw.png"  context.drawImage(drawing,0,0); 
like image 294
pixielex Avatar asked Jan 23 '12 19:01

pixielex


People also ask

Can a canvas element 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.

Do PNG images support transparency?

Raster file formats that support transparency include GIF, PNG, BMP, TIFF, TGA and JPEG 2000, through either a transparent color or an alpha channel.


1 Answers

Don't forget to add an event listener to the image's load event. Image loading is something that happens in the background, so when the JavaScript interpreter gets to the canvas.drawImage part it is most likely the image probably will not have loaded yet and is just an empty image object, without content.

drawing = new Image(); drawing.src = "draw.png"; // can also be a remote URL e.g. http:// drawing.onload = function() {    context.drawImage(drawing,0,0); }; 
like image 143
Menno Bieringa Avatar answered Sep 22 '22 18:09

Menno Bieringa