By reading this piece, you will learn to save a drawing on the HTML5 canvas element of your web application as an image. In this tutorial, I will be showcasing two methods to save it.

The first method is to store the image data inside a hyperlink (using the <a>tag). Then, you can download it manually from your browser via a manual click or trigger it programmatically using JavaScript. This option is good if you intend to let the users download it on their machine or just wanted to save a few images from the canvas.

As for the second method, I am going to convert the canvas as blob data and send it via FormData to a remote server. After that, you can easily save it on your server. This method is preferred if you are going to do data collection or saving a large amount of images from time to time.

Let’s proceed to the next section and start implementing it on your application

Canvas

If you already have an existing canvas, feel free to skip to the next section for hyperlink implementation.

We are going to set up the canvas now. Make sure that you have declared a canvas element in your HTML file.

<canvas id="output" />

Add the following code in the script tag or your external JavaScript file. It will draw a simple circle on the canvas.

let canvas = document.getElementById("output");
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();

#image #canvas #javascript #html #programming

How to Save HTML5 Canvas Drawing as anImage
1.85 GEEK