借助toDataURL实现将HTML5Canvas的内容保留为图片-
发布时间:09/01 来源:未知 浏览:
关键词:
HTML + JavaScript的代码很简略。
《script》 window.onload = function() { draw(); var saveButton = document.getElementById("saveImageBtn"); bindButtonEvent(saveButton, "click", saveImageInfo); var dlButton = document.getElementById("downloadImageBtn"); bindButtonEvent(dlButton, "click", saveAsLocalImage); }; function draw(){ var canvas = document.getElementById("thecanvas"); var ctx = canvas.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)"; // black color ctx.fillText("Gloomyfish - Demo", 50, 50); } function bindButtonEvent(element, type, handler) { if(element.addEventListener) { element.addEventListener(type, handler, false); } else { element.attachEvent('on'+type, handler); } } function saveImageInfo () { var mycanvas = document.getElementById("thecanvas"); var image = mycanvas.toDataURL("image/png"); var w=window.open('about:blank','image from canvas'); w.document.write(""); } function saveAsLocalImage () { var myCanvas = document.getElementById("thecanvas"); // here is the most important part because if you dont replace you will get a DOM 18 exception. // var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png"); var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); window.location.href=image; // it will save locally } 《script》
运转结果如下:
以上就是本文的全部内容,但愿对大家的学习有所帮忙,更多相干内容请关注百分百源码网!