Draw an image with opacity on the canvas

I have an image. I am using drawImage()

to paint it on canvas.

My question is, if the image has an opacity of 0.4, how will I draw it at the same opacity on the canvas.

I created a sample Fiddle here . How can I paint #scream

on mycanvas

while maintaining 0.4 the opacity of 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);
}

      

+3


source to share


1 answer


Use globalAlpha

, but make sure you set it before drawing the image:



ctx.globalAlpha = 0.4;

      

+9


source







All Articles