11

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

Amay
  • 1,461
  • 5
  • 27
  • 56
  • You have to change the global context, draw the image, then change it back for everything else. – mash Sep 22 '13 at 21:51

2 Answers2

25

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.

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 next thing drawn (which would be the image in this case).

And of course, you can always prep your image with an alpha-channel in case of PNG images.

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

You can also use save and restore.

context.save();
context.globalAlpha = 0.5;
.... 
context.restore();  //this will restore canvas state
ViliusL
  • 4,589
  • 26
  • 28