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

前端 未结 8 1071
庸人自扰
庸人自扰 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:24

    You can. Transparent canvas can be quickly faded by using destination-out global composite operation. It's not 100% perfect, sometimes it leaves some traces but it could be tweaked, depending what's needed (i.e. use 'source-over' and fill it with white color with alpha at 0.13, then fade to prepare the canvas).

    // Fill canvas using 'destination-out' and alpha at 0.05
    ctx.globalCompositeOperation = 'destination-out';
    ctx.fillStyle = "rgba(255, 255, 255, 0.05)";
    ctx.beginPath();
    ctx.fillRect(0, 0, width, height);
    ctx.fill();
    // Set the default mode.
    ctx.globalCompositeOperation = 'source-over';
    
    0 讨论(0)
  • 2020-11-27 10:25

    You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.

    If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.

    0 讨论(0)
提交回复
热议问题