JavaScript Canvas - change the opacity of image

前端 未结 2 1026
栀梦
栀梦 2020-12-10 15:32

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 3

相关标签:
2条回答
  • 2020-12-10 15:46

    You can also use save and restore.

    context.save();
    context.globalAlpha = 0.5;
    .... 
    context.restore();  //this will restore canvas state
    
    0 讨论(0)
  • 2020-12-10 15:47

    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;
    
    0 讨论(0)
提交回复
热议问题