标签:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <canvas id="drawing" style="width:200px;height:200px;background-color:#FC9"> A drawing of something </canvas> <button id="save">SavaImageBtn</button> <button id="download">DownLoadImageBtn</button> <script> var drawing = document.getElementById("drawing"); var save = document.getElementById("save"); var downLoad = document.getElementById("download"); window.onload = function(){ draw(); bindButtonEvent(save,"click",saveImageInfo); bindButtonEvent(downLoad,"click",saveAsLocalImage); } function draw() { var ctx = drawing.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)"; ctx.fillText("hello",150,50); } function bindButtonEvent(element,type,handler) { if(element.addEventListener) { element.addEventListener(type,handler,false); }else { element.attachEvent("on"+type,handler); } } function saveImageInfo() { var image = drawing.toDataURL("image/png"); document.body.innerHTML += image; var w = window.open("about:blank","image from canvas"); w.document.write("<img src=‘"+image+"‘/>"); } function saveAsLocalImage() { var image = drawing.toDataURL("image/png").replace("image/png","image/octet-stream"); window.location.href = image; } </script> </body> </html>
标签:
原文地址:http://www.cnblogs.com/pmx-pmx/p/5114078.html