Home > Web Front-end > HTML Tutorial > How to save canvas data to file in HTML5?

How to save canvas data to file in HTML5?

WBOY
Release: 2023-09-08 11:57:02
forward
970 people have browsed it

How to save canvas data to file in HTML5?

The canvas is just a rectangular area on the HTML page. We can draw graphics in this rectangular area (Canvas) with the help of JavaScript.

Canvas can be created in HTML5 as -

<canvas id = &rdquo;canvas1&rdquo; width = &rdquo;250&rdquo; height = &rdquo;150&rdquo;></canvas>                                 
Copy after login

This will create an empty canvas named canvas1, width=200, height=100.

To draw the graph in it we use JavaScript -

var canvas = document.getElementById("Canvas1");
 var ctx1 = canvas.getContext("2d");
ctx1.moveTo(0,0); ctx1.lineTo(300,200);
 ctx1.stroke(); // This method actually draw graphics as per context object             
Copy after login

To save this graph we need to save it as some data url like img.png or img.jpg

To do this, we will write -

var imgurl= canvas.toDataURL( ) ; / / This method saves graphics in png
document.getElementById(&lsquo;cimg&rsquo;).src = imgurl; // This will set img src to dataurl(png)
so that it can be saved as image.
Copy after login

This way, we can save the canvas data to an HTML5 file.

The above is the detailed content of How to save canvas data to file in HTML5?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
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