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

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

    Some simpler example code for using globalAlpha:

    ctx.save();
    ctx.globalAlpha = 0.4;
    ctx.drawImage(img, x, y);
    ctx.restore();
    

    If you need img to be loaded:

    var img = new Image();
    img.onload = function() {
        ctx.save();
        ctx.globalAlpha = 0.4;
        ctx.drawImage(img, x, y);
        ctx.restore()
    };
    img.src = "http://...";
    

    Notes:

    • Set the 'src' last, to guarantee that your onload handler is called on all platforms, even if the image is already in the cache.

    • Wrap changes to stuff like globalAlpha between a save and restore (in fact use them lots), to make sure you don't clobber settings from elsewhere, particularly when bits of drawing code are going to be called from events.

提交回复
热议问题