28

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);
}
Becky
  • 5,467
  • 9
  • 40
  • 73

1 Answers1

62

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

ctx.globalAlpha = 0.4;
Ibrahim
  • 1,209
  • 1
  • 11
  • 16
Puni
  • 1,214
  • 2
  • 18
  • 34
  • how can i add in only one ctx? – Narendra Solanki Oct 27 '17 at 10:20
  • 8
    @NarendraSolanki If I'm understanding your comment correctly, you could use `save()` and `restore()` before and after respectively to avoid making everything you draw afterwards use the same alpha value set here. – Ibrahim Jan 13 '18 at 14:15
  • sweet mother of midnight, I never knew you could do this! It saves so much headache with style isolation containers upon containers and overlapping canvasi... I should really read the docs next time XD – CCJ Nov 29 '20 at 04:32