Welcome folks today in this blog post we will be using the DOMToImage.js
and Filesaver.js library in javascript to take screenshot of the dom elements and save it as png or jpeg images. All the full source code of the application will be given below.
Get Started
In order to get started you need to make an index.html
file and copy paste the library cdn of domtoimage.js and filesaver.js as shown below
1 2 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script> |
Now after that guys we need to define some html in the browser so that we can take screenshot of it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<div id="content"> KANE WILLIAMSON IS THE CAPTAIN OF NEW ZEALAND </div> <button onclick="downloadImage()">download img</button> <style> #content { background: black; text-align: center; line-height: 100px; width: 600px; height: 100px; color: #fff; } </style> |
As you can see we have the div section and we have given the unique id to it which is content
so that we can target it inside the javascript. And inside it we have the h1
heading which says some text. And then we are styling it with some custom css. And then we have the button to take the screenshot as png or jpeg image.
1 2 3 4 5 6 7 8 |
var content = document.getElementById('content'); function downloadImage(){ domtoimage.toBlob(content) .then(function(blob) { window.saveAs(blob, 'my-node.png'); }); } |
As you can see we are calling the domtoimage()
library and inside it we are calling the method called toBlob()
which basically converts the DOM element to a blob object and then we save that blob as an attachment in the browser using the filesaver.js library. Now if you open the index.html
file inside the browser you will see the below result