How to save canvas data to file in HTML5?

HTMLJavascriptProgramming Scripts

A 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 = ”canvas1” width = ”250” height = ”150”></canvas>                                 

This creates an empty canvas with name canvas1 with width=200 and height=100.

 To draw graphics 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             

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

For this, we will write −

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

In this way, we can save canvas data to file in HTML5.

raja
Published on 21-Mar-2018 07:42:48
Advertisements