腾讯微群加入QQ群

 找回密码
 加入我们

!connect_header_login!

!connect_header_login_tip!

搜索
查看: 725|回复: 0

将HTML5 Canvas的内容保存为图片

[复制链接]
发表于 2016-8-23 14:57:53 | 显示全部楼层 |阅读模式

主要思想是借助Canvas自己的API - toDataURL()来实现,整个实现

HTML + JavaScript的代码很简单。

<html>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<head>
<script>
    	window.onload = function() {
    		draw();
    		var saveButton = document.getElementById("saveImageBtn");
    		bindButtonEvent(saveButton, "click", saveImageInfo);
    		var dlButton = document.getElementById("downloadImageBtn");
    		bindButtonEvent(dlButton, "click", saveAsLocalImage);
    	};
            function draw(){
                var canvas = document.getElementById("thecanvas");
                var ctx = canvas.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)"; // black color
                ctx.fillText("Gloomyfish - Demo", 50, 50);
            }
            
            function bindButtonEvent(element, type, handler)
            {
            	   if(element.addEventListener) {
            	      element.addEventListener(type, handler, false);
            	   } else {
            	      element.attachEvent('on'+type, handler);
            	   }
			}
            
            function saveImageInfo () 
            {
            	var mycanvas = document.getElementById("thecanvas");
            	var image    = mycanvas.toDataURL("image/png");
            	var w=window.open('about:blank','image from canvas');
            	w.document.write("<img src='"+image+"' alt='from canvas'/>");
            }

            function saveAsLocalImage () {
            	var myCanvas = document.getElementById("thecanvas");
        		// here is the most important part because if you dont replace you will get a DOM 18 exception.
        		// var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png");
        		var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 
        		window.location.href=image; // it will save locally
        	}
        </script>
</head>
<body bgcolor="#E6E6FA">
	<div>
		<canvas width=200 height=200 id="thecanvas"></canvas>
		<button id="saveImageBtn">Save Image</button>
		<button id="downloadImageBtn">Download Image</button>
	</div>
</body>
</html>

运行效果如下:



1
52

转自:http://blog.csdn.net/jia20003/article/details/8948005?locationNum=3
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入我们

本版积分规则

QQ|手机版|Archiver|小黑屋|一起疯|苦咖啡 ( 新ICP备12000197号  

GMT+8, 2018-6-18 23:04 , Processed in 0.041951 second(s), 12 queries , Memcache On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表