Home > Web Front-end > H5 Tutorial > Save the content of HTML5 Canvas as an image using toDataURL_html5 tutorial skills

Save the content of HTML5 Canvas as an image using toDataURL_html5 tutorial skills

WBOY
Release: 2016-05-16 15:49:28
Original
1342 people have browsed it

The main idea is to use Canvas' own API - toDataURL() to achieve it. The entire implementation
HTML JavaScript code is very simple.

Copy code
The code is as follows:


< meta http-equiv="X-UA-Compatible" content="chrome=1">

<script> <br>window.onload = function() { <br>draw (); <br>var saveButton = document.getElementById("saveImageBtn"); <br>bindButtonEvent(saveButton, "click", saveImageInfo); <br>var dlButton = document.getElementById("downloadImageBtn"); <br> bindButtonEvent(dlButton, "click", saveAsLocalImage); <br>}; <br>function draw(){ <br>var canvas = document.getElementById("thecanvas"); <br>var ctx = canvas.getContext(" 2d"); <br>ctx.fillStyle = "rgba(125, 46, 138, 0.5)"; <br>ctx.fillRect(25,25,100,100); <br>ctx.fillStyle = "rgba( 0, 146, 38, 0.5)"; <br>ctx.fillRect(58, 74, 125, 100); <br>ctx.fillStyle = "rgba( 0, 0, 0, 1)"; // black color <br>ctx .fillText("Gloomyfish - Demo", 50, 50); <br>} <br>function bindButtonEvent(element, type, handler) <br>{ <br>if(element.addEventListener) { <br>element.addEventListener (type, handler, false); <br>} else { <br>element.attachEvent('on' type, handler); <br>} <br>} <br>function saveImageInfo () <br>{ <br>var mycanvas = document.getElementById("thecanvas"); <br>var image = mycanvas.toDataURL("image/png"); <br>var w=window.open('about:blank','image from canvas '); <br>w.document.write("<img src='" image "' alt='from canvas'/>"); <br>} <br>function saveAsLocalImage () { <br> var myCanvas = document.getElementById("thecanvas"); <br>// here is the most important part because if you dont replace you will get a DOM 18 exception. <br>// var image = myCanvas.toDataURL("image /png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png"); <br>var image = myCanvas.toDataURL("image/png") .replace("image/png", "image/octet-stream"); ​​<br>window.location.href=image; // it will save locally <br>} <br></script>







< ;/body>


The operation effect is as follows:
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template