HTML5技术

将HTML5 Canvas的内容保存为图片 - jerrylsxu

字号+ 作者:H5之家 来源:博客园 2015-12-15 12:40 我要评论( )

主要思想是借助Canvas自己的API - toDataURL()来实现,整个实现 HTML + JavaScript的代码很简单。 代码如下: 1 html 2 meta http-equiv="X-UA-Compatible" content="chrome=1" 3 head 4 script 5window.onload = function() { 6draw(); 7var saveButton = d

主要思想是借助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></canvas> 52 <button>Save Image</button> 53 <button>Download Image</button> 54 </div><a href=http://www.cnblogs.com/roucheng/">柔城</a> 55 </body> 56 </html>

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • HTML5 进阶系列:拖放 API 实现拖放排序 - _林鑫

    HTML5 进阶系列:拖放 API 实现拖放排序 - _林鑫

    2017-05-02 11:02

  • HTML5 进阶系列:indexedDB 数据库 - _林鑫

    HTML5 进阶系列:indexedDB 数据库 - _林鑫

    2017-04-27 14:02

  • HTML5 高级系列:web Storage - _林鑫

    HTML5 高级系列:web Storage - _林鑫

    2017-04-27 14:01

  • HTML5和CSS3 - 奔跑在起跑线佼佼者

    HTML5和CSS3 - 奔跑在起跑线佼佼者

    2017-04-20 13:00

网友点评