javascript 在画布上绘制不透明的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31708618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
draw image with opacity on to a canvas
提问by Becky
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.
我在这里创建了一个示例Fiddle。我怎样才能保持图像的不透明度#scream
为mycanvas
0.4。
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);
}
回答by Puni
Use globalAlpha
but make sure that you set it before drawing the image:
使用globalAlpha
但请确保在绘制图像之前设置它:
ctx.globalAlpha = 0.4;