Home >Web Front-end >H5 Tutorial >Use toDataURL to save the content of HTML5 Canvas as an image
The main idea of saving the content of HTML5 Canvas as images is to use Canvas' own API - toDataURL(). The specific implementation is as follows. Interested friends can refer to it. I hope it will be helpful to you.
The main idea is to use Canvas' own API - toDataURL() to achieve it. The entire
HTML JavaScript code is very simple.
<html> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <head> <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("<img src='"+image+"' alt='from canvas'/>"); } 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> </head> <body bgcolor="#E6E6FA"> <p> <canvas width=200 height=200 id="thecanvas"></canvas> <button id="saveImageBtn">Save Image</button> <button id="downloadImageBtn">Download Image</button> </p> </body> </html>
The operation effect is as follows:
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please Follow PHP Chinese website!
Related recommendations:
About HTML5
Canvas event handling
angularJS combined with canvas drawing implementation
The above is the detailed content of Use toDataURL to save the content of HTML5 Canvas as an image. For more information, please follow other related articles on the PHP Chinese website!