JavaScript canvas - changing the opacity of an image

I am trying to create a platform in Canvas. I have a main character and some enemies. When a player touches an enemy, he will lose some HP, and he will be untouchable for about 3 seconds. Now I have one problem. After losing HP, I want to set the opacity of the character image to 0.5 (to show this untouchable thing).

var mainchar = new Image(); mainchar.src = 'mainch.png'; 

I do not want to use ctx.globalCompositeOperation = "lighter" or ctx.globalAlpha = 0.5 , because both of them change the opacity of all elements (this is global). Is there a way to change the transparency of the image? For example, "mainchar.changeopacity"?

+6
source share
2 answers

You need to either modify globalAlpha , or draw an image on the screen canvas with globalAlpha , and then apply this canvas to the main canvas.

Just set alpha, draw an image and reset alpha back to full opacity. Setting the alpha channel does not change the content that is already drawn on the canvas - it applies only to the next figure (in this case it will be an image).

And, of course, you can always prepare your image for the alpha channel in the case of PNG images.

 /// only image will have alpha affected: context.globalAlpha = 0.5; context.drawImage(image, x, y); context.globalAlpha = 1.0; 
+15
source

use save and restore:

 canvas.save(); canvas.globalAlpha = 0.5; .... canvas.restore(); //this will restore canvas state 
+4
source

Source: https://habr.com/ru/post/954370/


All Articles