首页 > web前端 > H5教程 > 将HTML5 Canvas的内容保存为图片借助toDataURL实现_html5教程技巧

将HTML5 Canvas的内容保存为图片借助toDataURL实现_html5教程技巧

WBOY
发布: 2016-05-16 15:49:28
原创
1342 人浏览过

主要思想是借助Canvas自己的API - toDataURL()来实现,整个实现
HTML + JavaScript的代码很简单。

复制代码
代码如下:




<script> <br />window.onload = function() { <br />draw(); <br />var saveButton = document.getElementById("saveImageBtn"); <br />bindButtonEvent(saveButton, "click", saveImageInfo); <br />var dlButton = document.getElementById("downloadImageBtn"); <br />bindButtonEvent(dlButton, "click", saveAsLocalImage); <br />}; <br />function draw(){ <br />var canvas = document.getElementById("thecanvas"); <br />var ctx = canvas.getContext("2d"); <br />ctx.fillStyle = "rgba(125, 46, 138, 0.5)"; <br />ctx.fillRect(25,25,100,100); <br />ctx.fillStyle = "rgba( 0, 146, 38, 0.5)"; <br />ctx.fillRect(58, 74, 125, 100); <br />ctx.fillStyle = "rgba( 0, 0, 0, 1)"; // black color <br />ctx.fillText("Gloomyfish - Demo", 50, 50); <br />} <br />function bindButtonEvent(element, type, handler) <br />{ <br />if(element.addEventListener) { <br />element.addEventListener(type, handler, false); <br />} else { <br />element.attachEvent('on'+type, handler); <br />} <br />} <br />function saveImageInfo () <br />{ <br />var mycanvas = document.getElementById("thecanvas"); <br />var image = mycanvas.toDataURL("image/png"); <br />var w=window.open('about:blank','image from canvas'); <br />w.document.write("<img src='"+image+"' alt='from canvas'/>"); <br />} <br />function saveAsLocalImage () { <br />var myCanvas = document.getElementById("thecanvas"); <br />// here is the most important part because if you dont replace you will get a DOM 18 exception. <br />// var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png"); <br />var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); <br />window.location.href=image; // it will save locally <br />} <br /></script>










运行效果如下
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板