How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

前端 未结 8 1141
庸人自扰
庸人自扰 2020-11-27 09:51

Using the HTML5 element, I would like to load an image file (PNG, JPEG, etc.), draw it to the canvas completely transparently, and then fade it i

8条回答
  •  野性不改
    2020-11-27 10:07

    I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.

    //works with shapes but not with images
    ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
    

    I have concluded that setting the globalCompositeOperation works with images.

    //works with images
    ctx.globalCompositeOperation = "lighter";
    

    I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.

    EDIT:

    After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha parameter BEFORE you draw the image:

    //works with images
    ctx.globalAlpha = 0.5
    

    If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout function, look that up to create a loop from which you alter the alpha over time.

提交回复
热议问题