Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Canvas - change the opacity of image

Tags:

People also ask

How to change opacity of image in canvas?

html5-canvas Compositing Change opacity with "globalAlpha" You can change the opacity of new drawings by setting the globalAlpha to a value between 0.00 (fully transparent) and 1.00 (fully opaque). The default globalAlpha is 1.00 (fully opaque). Existing drawings are not affected by globalAlpha .

What is ctx globalAlpha?

Definition and Usage. The globalAlpha property sets or returns the current alpha or transparency value of the drawing. The globalAlpha property value must be a number between 0.0 (fully transparent) and 1.0 (no transparancy). Default value: 1.0.


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).

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' ?