Converting Any HTML DOM Node to an SVG PNG or JPG Image
Posted By : Nisheet Sharma | 27-Apr-2018
Converting any HTML DOM node to an SVG/PNG/JPG Image
dom-to-image is a JavaScript plugin, that can be used to convert any HTML5 DOM node, to an SVG vector image or PNG/JPG raster image.
Installation:
1. We can install is via
2. Then, all you need to do is, add the dom-to-image.min.js file,
from the dist folder of the
Usage:
After, you include the minified js file to your HTML file,
you can use the
This variable is available on the Global scope, so you can access it any script file or
The functions available to generate Images are as follows:
1. toPng - To get a PNG image
2. toBlob - To get a PNG blob image, which would be useful if you want to store it in a database.
3. toJpeg - To get a JPEG image
4. toSvg - To get an SVG vector image
5. toPixelData - To get Uint8Array format raw pixel data.
All of the above mentioned functions can have the following arguments:
1. node - This is the HTML element, whose contents will be converted to an image.
2. options - This is an optional parameter, we can use to configure the image as we want. Like, increase/decrease quality, size, filter out anything etc.
These functions return a Promise when we execute them. And if successfully executed they return a dataURL as the response.
You can then, use the dataURL to display an image directly into your page, or download it, or send it to your backend to be saved.
A Simple example to convert a DOM node to an image and display it directly
domtoimage.toPng(document.getElementById('id-of-the-node-you-want-to-convert'))
.then(dataURL => {
var image = new Image();
image.src = dataURL;
document.body.appendChild(image);
})
.catch(error => console.error('Something went wrong!', error));
Now lets, say we want a JPG image, and the anchor tags removed from the final image, also we want to reduce the quality of the final image down to 80% and download it, then do this:
domtoimage.toJpeg(document.getElementById('id-of-the-node-you-want-to-convert'), {
quality: 0.80,
filter: node => node.tagName !== 'a'
})
.then(function (dataUrl) {
var link = document.createElement('a');
link.download = 'sample-image-name.jpeg';
link.href = dataUrl;
link.click();
});
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Nisheet Sharma
Nisheet is a Full Stack Developer (MEAN). He is familiar with C, C++, Java, Html, Css, JavaScript, MySql, MongoDb, AngularJs, NodeJs, ExpressJs.