How to draw transparent image with html5 canvas element

╄→尐↘猪︶ㄣ 提交于 2019-12-30 01:55:27

问题


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.


回答1:


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




回答2:


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

<!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.




回答3:


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.



来源:https://stackoverflow.com/questions/2916938/how-to-draw-transparent-image-with-html5-canvas-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!