Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

draw image with opacity on to a canvas [duplicate]

I've got an image. I use drawImage() to draw it on to a canvas.

My question is: If the image has an opacity of 0.4, how do I draw it in the same opacity on to the canvas.

I've created a sample Fiddle here. How can I draw #scream on to mycanvas maintaining 0.4 opacity on the image.

html:

<p>Image with 0.4 opacity to be used:</p>
<img id="scream" width="200" height="200" src="http://img42.com/NMMU8+">

<p>Canvas:</p>
<canvas id="myCanvas" width="220" height="220" style="border:1px solid #d3d3d3;">
</canvas>

css:

#scream{
    opacity: 0.4;
}
#myCanvas{
    background-color: #f60;
}

js:

window.onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img, 10, 10);
}
like image 491
Becky Avatar asked Jul 29 '15 18:07

Becky


People also ask

What is canvas globalAlpha?

globalAlpha property of the Canvas 2D API specifies the alpha (transparency) value that is applied to shapes and images before they are drawn onto the canvas.

Which element is used to represent the transparency of an element in CSS?

CSS Opacity / TransparencyThe opacity property specifies the opacity/transparency of an element.


1 Answers

Use globalAlpha but make sure that you set it before drawing the image:

ctx.globalAlpha = 0.4;
like image 200
Puni Avatar answered Sep 21 '22 06:09

Puni