码迷,mamicode.com
首页 > 其他好文 > 详细

将canvas的内容转成图片

时间:2016-01-08 18:47:08      阅读:332      评论:0      收藏:0      [点我收藏+]

标签:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
    <canvas id="drawing" style="width:200px;height:200px;background-color:#FC9">
        A drawing of something
    </canvas>
   <button id="save">SavaImageBtn</button>
   <button id="download">DownLoadImageBtn</button>
   
    <script>
        var drawing = document.getElementById("drawing");
        var save = document.getElementById("save");
        var downLoad = document.getElementById("download");
        
        window.onload = function(){
            draw();
            bindButtonEvent(save,"click",saveImageInfo);
            bindButtonEvent(downLoad,"click",saveAsLocalImage);        
        }
        
        function draw()
        {
            var ctx = drawing.getContext("2d");    
            ctx.fillStyle = "rgba(125,46,138,0.5)";
            ctx.fillRect(25,25,100,100);
            ctx.fillStyle = "rgba(0,146,38,0.5)";
            ctx.fillRect(58,74,125,100);
            ctx.fillStyle = "rgba(0,0,0,1)";
            ctx.fillText("hello",150,50);
        }
        
        function bindButtonEvent(element,type,handler)
        {
            if(element.addEventListener)
            {
                element.addEventListener(type,handler,false);    
            }else
            {
                element.attachEvent("on"+type,handler);    
            }
        }
        
        function saveImageInfo()
        {
            var image = drawing.toDataURL("image/png");
            document.body.innerHTML += image;
            var w = window.open("about:blank","image from canvas");
            w.document.write("<img src=‘"+image+"‘/>");
        }
        
        function saveAsLocalImage()
        {
            var image = drawing.toDataURL("image/png").replace("image/png","image/octet-stream");
            window.location.href = image;
        }
    </script>
</body>
</html>

 

将canvas的内容转成图片

标签:

原文地址:http://www.cnblogs.com/pmx-pmx/p/5114078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!