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

前端 未结 8 1147
庸人自扰
庸人自扰 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';
    

提交回复
热议问题