JavaScript Canvas - 改变图像的不透明度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18949122/
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
JavaScript Canvas - change the opacity of image
提问by Amay
I'm trying to create a platform game in Canvas. I have main character and some enemies. When player touch enemy, he will lose some HP and he will be untouchable for about 3s. Now I have one problem. After loosing HP, I want to set opacity of character image to 0.5 (to show that untouchable thing).
我正在尝试在 Canvas 中创建一个平台游戏。我有主角和一些敌人。当玩家接触到敌人时,他会损失一些HP,并且在大约3秒内无法触及。现在我有一个问题。失去HP后,我想将角色图像的不透明度设置为0.5(以显示不可触摸的东西)。
var mainchar = new Image();
mainchar.src = 'mainch.png';
I don't want to use ctx.globalCompositeOperation = "lighter"
or ctx.globalAlpha = 0.5
becouse both of them change the opacity of all elements (it's global). Is there any way to change the image opacity? For example 'mainchar.changeopacity' ?
我不想使用ctx.globalCompositeOperation = "lighter"
或ctx.globalAlpha = 0.5
因为它们都改变所有元素的不透明度(它是全局的)。有没有办法改变图像的不透明度?例如'mainchar.changeopacity'?
回答by
You have to either change globalAlpha
or draw the image to an off-screen canvas that has globalAlpha
set, then draw this canvas onto the main canvas.
您必须globalAlpha
将图像更改或绘制到已globalAlpha
设置的屏幕外画布,然后将此画布绘制到主画布上。
Just set alpha, draw the image and reset alpha back to full opacity. Setting alpha does not change the content that is already drawn to the canvas - it only applies to the nextthing drawn (which would be the image in this case).
只需设置 alpha,绘制图像并将 alpha 重置回完全不透明度。设置 alpha 不会改变已经绘制到画布上的内容——它只适用于下一个绘制的东西(在这种情况下就是图像)。
And of course, you can always prep your image with an alpha-channel in case of PNG images.
当然,对于 PNG 图像,您始终可以使用 alpha 通道准备图像。
/// only image will have alpha affected:
context.globalAlpha = 0.5;
context.drawImage(image, x, y);
context.globalAlpha = 1.0;
回答by ViliusL
You can also use save and restore.
您还可以使用保存和恢复。
context.save();
context.globalAlpha = 0.5;
....
context.restore(); //this will restore canvas state