主要思想是借助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>
运行效果如下: