主要思想是借助Canvas自己的API - toDataURL()来实现,整个实现
HTML + JavaScript的代码很简单。
代码如下:
1 <html> 2 <meta http-equiv="X-UA-Compatible" content="chrome=1"> 3 <head> 4 <script> 5 window.onload = function() { 6 draw(); 7 var saveButton = document.getElementById("saveImageBtn"); 8 bindButtonEvent(saveButton, "click", saveImageInfo); 9 var dlButton = document.getElementById("downloadImageBtn"); 10 bindButtonEvent(dlButton, "click", saveAsLocalImage); 11 }; 12 function draw(){ 13 var canvas = document.getElementById("thecanvas"); 14 var ctx = canvas.getContext("2d"); 15 ctx.fillStyle = "rgba(125, 46, 138, 0.5)"; 16 ctx.fillRect(25,25,100,100); 17 ctx.fillStyle = "rgba( 0, 146, 38, 0.5)"; 18 ctx.fillRect(58, 74, 125, 100); 19 ctx.fillStyle = "rgba( 0, 0, 0, 1)"; // black color 20 ctx.fillText("Gloomyfish - Demo", 50, 50); 21 } 22 23 function bindButtonEvent(element, type, handler) 24 { 25 if(element.addEventListener) { 26 element.addEventListener(type, handler, false); 27 } else { 28 element.attachEvent(‘on‘+type, handler); 29 } 30 } 31 32 function saveImageInfo () 33 { 34 var mycanvas = document.getElementById("thecanvas"); 35 var image = mycanvas.toDataURL("image/png"); 36 var w=window.open(‘about:blank‘,‘image from canvas‘); 37 w.document.write("<img src=‘"+image+"‘ alt=‘from canvas‘/>"); 38 } 39 40 function saveAsLocalImage () { 41 var myCanvas = document.getElementById("thecanvas"); 42 // here is the most important part because if you dont replace you will get a DOM 18 exception. 43 // var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png"); 44 var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 45 window.location.href=image; // it will save locally 46 } 47 </script> 48 </head> 49 <body bgcolor="#E6E6FA"> 50 <div> 51 <canvas width=200 height=200 id="thecanvas"></canvas> 52 <button id="saveImageBtn">Save Image</button> 53 <button id="downloadImageBtn">Download Image</button> 54 </div><a href=http://www.cnblogs.com/roucheng/">柔城</a> 55 </body> 56 </html>