在画布上绘制不透明的图像 [英] draw image with opacity on to a canvas

查看:32
本文介绍了在画布上绘制不透明的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张图片.我使用 drawImage() 将其绘制到画布上.

I've got an image. I use drawImage() to draw it on to a canvas.

我的问题是:如果图像的不透明度为 0.4,我如何以相同的不透明度将其绘制到画布上.

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.

我已经创建了一个示例Fiddle here.如何将 #scream 绘制到 mycanvas 上,保持图像的 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:

<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 但请确保在绘制图像之前设置它:

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

ctx.globalAlpha = 0.4;

这篇关于在画布上绘制不透明的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆