大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。
主要思想是借助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>
http://www.cnblogs.com/roucheng/
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/120724.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...