If you wish to take a screenshot of half or your entire net web page utilizing JavaScript, you may end up caught. Creating a picture from an HTML component can seem to be a problem, as there isn’t any direct solution to do it in JavaScript.
Fortunately, this is not an unattainable job and is, actually, fairly simple with the correct instruments. Utilizing the html-to-image library, making pictures of DOM nodes is so simple as a single perform name.
How Does html-to-image Work?
The html-to-image library produces a picture within the type of a base64 information URL. It helps a number of output codecs, together with PNG, JPG, and SVG. To carry out this conversion, the library makes use of this algorithm:
- Create a clone of the goal HTML component, its kids, and any connected pseudo-elements.
- Copy the styling for all cloned components and embed the styling inline.
- Embed the related net fonts, if there are any.
- Embed any pictures current.
- Convert the cloned node into XML, after which SVG.
- Use the SVG to create a Information URL.
Caveats and Limitations
Regardless that html-to-image is a superb library, it isn’t good. It has a number of caveats, specifically:
- The library won’t work in Web Explorer or Safari.
- If the HTML you attempt to convert features a tainted canvas component, the library will fail. As MDN explains, together with non-CORS-approved information in your canvas component will taint it.
- As a result of browsers place limits on the utmost measurement of a knowledge URL, there are limits on the scale of the HTML the library can convert.
Utilizing the Library
To attempt the library out, the very first thing it’s good to do is create a mission listing in your native machine. Subsequent, set up html-to-image in that listing utilizing the npm package manager. Here is the terminal command to put in it:
npm set up
You also needs to set up a JavaScript bundler, to make it a bit simpler to make use of the library. The esbuild bundler might help bundle node modules into web-compatible scripts.
npm set up esbuild
That is all it’s good to set up. Subsequent, create a file known as index.html in your listing, and serve it with an online server of your alternative. Put the next code in index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta title="viewport"
content material="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Appropriate" content material="ie=edge">
<title>Doc</title>
<model>
.colorful-div
padding: 3rem;
colour: white;
background-image: linear-gradient(to proper, yellow, rebeccapurple);
border: 1px strong black;
margin: 1rem auto;
font-size: 3rem;
font-family: cursive;
</model>
</head>
<physique>
<div class="colorful-div">
I'm going to be in a screenshot!
</div>
<div class="long-text">
I'm an instance of a sufficiently verbose paragraph that
illustrates that taking screenshots in JavaScript is
actually very simple, for the next causes:
<ul>
<li>Cause 1</li>
<li>Cause 2</li>
<li>Cause 2</li>
</ul>
</div><script src="out.js"></script>
</physique>
</html>
This code creates two components on the web page: a div with a gradient background, and a few textual content and an unordered listing inside one other div. Subsequent, you will write the JavaScript to transform these components to pictures. Put the next code in a brand new file known as script.js:
import * as htmlToImage from "html-to-image";const elems = ['.colorful-div', '.long-text']
elems.forEach((elem, ind) =>
const node = doc.querySelector(elem)
htmlToImage.toPng(node)
.then(perform (dataUrl)
let img = new Picture();
img.src = dataUrl;
doc.physique.appendChild(img);
)
.catch(perform (error)
console.error('oops, one thing went flawed!');
console.log(error)
);
)
This code does a number of issues:
- Imports the html-to-image library.
- Creates an array manufactured from CSS selectors concentrating on the 2 components.
- Creates a PNG picture within the type of a knowledge URL from every component of the array.
- Creates an img tag and units its src attribute to the info URL, creating picture copies of the 2 components.
Now use esbuild to generate the bundled file (out.js) that index.html references by operating the next in your terminal:
./node_modules/.bin/esbuild script.js
At this level, this is what index.html ought to seem like in your browser:
Regardless that the copies look precisely the identical because the originals, they’re truly picture components. You possibly can affirm this by opening your dev tools and inspecting them.
This library additionally works with JavaScript frameworks. The html-to-image documentation comprises directions on find out how to generate different picture codecs. It additionally consists of an instance displaying find out how to use the library with React.
Taking Screenshots With JavaScript Is Simple
There is no native JavaScript methodology for creating pictures from HTML components, or taking screenshots of the DOM. Nonetheless, with the assistance of libraries and companies like html-to-image, it turns into a straightforward job.
There are different methods of attaining related outcomes, such because the wkhtmltoimage library. You should use this open-source software to take screenshots of a whole net web page.