This question already has an answer here:
这个问题已经有了答案:
- How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn? 7 answers
- 如何更改画布元素中元素的不透明度(alpha,透明度)?7的答案
I've got an image. I use drawImage()
to draw it on to a canvas.
我有一个图像。我使用drawImage()将其绘制到画布上。
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.
我的问题是:如果图像的不透明度是0.4,我如何在画布上使用同样的不透明度来绘制它呢?
I've created a sample Fiddle here. How can I draw #scream
on to mycanvas
maintaining 0.4 opacity on the image.
我在这里创建了一个样本。我怎样才能把# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
html:
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:
css:
#scream{
opacity: 0.4;
}
#myCanvas{
background-color: #f60;
}
js:
js:
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
}
1 个解决方案
#1
11
Use globalAlpha
but make sure that you set it before drawing the image:
使用globalAlpha,但请确保在绘制图像之前设置:
ctx.globalAlpha = 0.4;
#1
11
Use globalAlpha
but make sure that you set it before drawing the image:
使用globalAlpha,但请确保在绘制图像之前设置:
ctx.globalAlpha = 0.4;