将 PNG 绘制到画布元素——不显示透明度
我正在尝试使用drawImage 在画布元素上绘制半透明PNG。但是,它将图像绘制为完全不透明。当我查看正在加载的资源并在浏览器中加载实际的 PNG 时,它会显示透明度,但当我在画布上绘制它时,它不会。有什么想法吗?
这是代码:
drawing = new Image()
drawing.src = "draw.png"
context.drawImage(drawing,0,0);
I'm trying to use drawImage to draw a semi-transparent PNG on a canvas element. However, it draws the image as completely opaque. When I look at the resource that's being loaded and load the actual PNG in the browser, it shows the transparency, but when I draw it on the canvas, it does not. Any ideas?
Here's the code:
drawing = new Image()
drawing.src = "draw.png"
context.drawImage(drawing,0,0);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不要忘记向图像的加载事件添加事件侦听器。图像加载是在后台发生的事情,因此当 JavaScript 解释器到达 canvas.drawImage 部分时,图像很可能尚未加载,只是一个没有内容的空图像对象。
Don't forget to add an event listener to the image's load event. Image loading is something that happens in the background, so when the JavaScript interpreter gets to the canvas.drawImage part it is most likely the image probably will not have loaded yet and is just an empty image object, without content.
您可以使用
Image
对象简单地插入任何透明图像:You can simply insert any transparent image using
Image
object:如果您在渲染循环中绘制它,则需要确保首先运行
context.clearRect( 0, 0, width, height )
,否则您只是在每帧的 png 上写入 png ,最终将是不透明的。 (但是帧渲染速度很快,所以你用肉眼看不到这一点。)If you are drawing it in a render loop, you need to make sure to run
context.clearRect( 0, 0, width, height )
first, otherwise you are just writing the png over the png every frame, which will eventually be opaque. (But frames render fast, so you wouldn't see this with the naked eye.)它应该工作得很好,你确定你的图像真的是透明的,而不仅仅是背景是白色的吗?
下面是在黑色矩形上绘制透明 PNG 的示例,以作为代码的基础:
http://jsfiddle.net/5P2Ms /
It ought to work fine, are you sure your image is really transparent and not just white in the background?
Here's an example of drawing a transparent PNG over a black rectangle to base your code off of:
http://jsfiddle.net/5P2Ms/
注意,如果您要使用
canvas.toDataURL
并将 mimetype 设置为gif
或png
以外的任何内容,则图像的透明部分图像将是全黑的。NB, if you was to use
canvas.toDataURL
and you set the mimetype to anything other than saygif
orpng
, the transparent parts of the image will be completely black.