Categories
JavaScript Answers

How to Capture the Content of an HTML Canvas as an Image File?

Spread the love

Sometimes we may want to capture the content of an HTML canvas as an image file.

In this article, we’ll look at ways that we can do that with JavaScript.

Capturing the Canvas

We can capture the canvas by using the toDataURL method that comes with the canvas element object.

For instance, we can write the following HTML:

<canvas></canvas>

Then we can write the following JavaScript to draw some content and capture it as an image file:

const canvas = document.querySelector("canvas");  
const context = canvas.getContext("2d");  
context.fillStyle = "lightblue";  
context.fillRect(50, 50, 100, 100);  
window.location = canvas.toDataURL("image/png");

We get the canvas element with querySelector .

Then we get the canvas context with getContext .

Then we set the fill style with fillStyle .

And we draw a rectangle with fillRect .

Then we just call toDataURL on the canvas with the MIME type of the file we want to generate to capture the canvas and turn it into a base64 string.

Capturing the Canvas to PDF

To capture the canvas and turn it into a PDF, we can use the jaPDF library.

To use it, we write the following HTML:

<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>  
<canvas></canvas>

Then we can add the JavaScript code to do the capture by writing:

const { jsPDF } = window.jspdf;  
const canvas = document.querySelector("canvas");  
const context = canvas.getContext("2d");  
context.fillStyle = "lightblue";  
context.fillRect(50, 50, 100, 100);  
const imgData = canvas.toDataURL("image/png");  
const doc = new jsPDF('p', 'mm');  
doc.addImage(imgData, 'PNG', 10, 10);  
doc.save('sample.pdf');

First we get the jsPDF object from the jspdf global variable added from the script tag.

Then the next 4 lines are the same as in the previous example.

Then we call canvs.toDataURL and assign the returned base64 string to imgData .

Next, we create a new jsPDF document object with the jsPDF constructor.

The first argument is the orientation of the document. p means portait.

The 2nd argument is the unit, and mm is millimeters.

Then we call addImage with imgData to add the image to our document.

The 2nd argument is the format.

The 3rd and 4th arguments are the x and y coordinates of the image relative to the upper edge of the page.

Then we call doc.save with the file name and extension to save the PDF.

Conclusion

We can capture a canvas’ content to an image with the toDataURL method.

And we can put the image into a PDF with the jsPDF library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *