HT ML + JavaScript的代码很 简单 。
<html> < ;m eta http-equiv="X-UA-Compatible" content="ch rom e=1"> <head> <script> window.onload = function() { draw(); VAR saveButton = document.getElementById("sav ei mage BT n"); 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("Gloomy Fish - Demo", 50, 50); } function bindButtonEvent(element, ty PE , handler) { if(element.addEventListener) { element.addEventListener(type, handler, false); } else { element.attachEvent(& # 39;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.wr IT e("< 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 -s tre am ;Content-Disposition: attachment;filename=foobar.png"); var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); window.location. hr ef=image; // it will save locally } </script> </head> <body bgcolor="#E6E6FA"> <p> <canvas width=200 height=200 id="thecanvas"></canvas> <button id="saveImageBtn">Save Image</button> <button id="downloadImageBtn">Download Image</button> </p> </body> </html>
运行效果如下 :
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
关于HTML5
Canvas的 事件处理
Angular JS结合canvas画图的实现
以上就是借助toDataURL实现将HTML5 Canvas的内容保存为图片的详细内容,更多请关注其它相关 文章 !
总结
以上是 为你收集整理的 借助toDataURL实现将HTML5 Canvas的内容保存为图片 全部内容,希望文章能够帮你解决 借助toDataURL实现将HTML5 Canvas的内容保存为图片 所遇到的问题。
如果觉得 网站内容还不错, 推荐好友。
查看更多关于借助toDataURL实现将HTML5 Canvas的内容保存为图片的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did204291