Javascript 如何使用 html5 canvas 元素绘制透明图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2916938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:28:50  来源:igfitidea点击:

How to draw transparent image with html5 canvas element

javascripthtmlcanvastransparency

提问by Mr Bell

I am targeting google chrome. Is it possible to draw transparent images on a canvas? By transparent I mean the drawing the entire image at something like 50% opacity.

我的目标是谷歌浏览器。是否可以在画布上绘制透明图像?透明是指以 50% 的不透明度绘制整个图像。

回答by james.garriss

You can do this using the globalAlpha property, like this:

您可以使用 globalAlpha 属性执行此操作,如下所示:

<!DOCTYPE HTML>
<html>
    <body>
        <canvas height="100" width="100" id="myCanvas"></canvas>
        <script>
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.globalAlpha = 0.5;
            var myImage = new Image();
            myImage.src = "someImage.jpg";
            myImage.onload = function()
            {
                context.drawImage(myImage, 0, 0, 100, 100);
            };
        </script>
    </body>
</html>

And yes, it does work with images. Verified with IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.

是的,它确实适用于图像。在 Win 7 上通过 IE 9、FF 5、Safari 5 和 Chrome 12 验证。

回答by Eric Mickelsen

The canvas element has a global alpha attribute that lets you apply partial transparency to anything you draw.

canvas 元素具有全局 alpha 属性,可让您将部分透明度应用于您绘制的任何内容。

回答by Patrick Wied

It's possible if you iterate thru the canvas' image-data and set the alpha value manually, then export the transparent image with the canvas.toDataURL method and insert it into another canvas.

如果您遍历画布的图像数据并手动设置 alpha 值,然后使用 canvas.toDataURL 方法导出透明图像并将其插入另一个画布,则是可能的。