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);
}
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.
CSS Opacity / TransparencyThe opacity property specifies the opacity/transparency of an element.
Use globalAlpha
but make sure that you set it before drawing the image:
ctx.globalAlpha = 0.4;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With