Friday, March 24, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home JavaScript

How to Convert HTML to an Image in JavaScript

learningcode_x1mckf by learningcode_x1mckf
September 16, 2022
in JavaScript
0
How to Convert HTML to an Image in JavaScript
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


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:

  1. Create a clone of the goal HTML component, its kids, and any connected pseudo-elements.
  2. Copy the styling for all cloned components and embed the styling inline.
  3. Embed the related net fonts, if there are any.
  4. Embed any pictures current.
  5. Convert the cloned node into XML, after which SVG.
  6. 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:

a demo page for html-to-image

You might also like

Toolkit Allows JavaScript Devs to Program Embedded Devices – The New Stack

Select data value from grandparent div? – JavaScript – SitePoint

How to Handle Errors in JavaScript – Programming – MUO – MakeUseOf

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.



Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

Toolkit Allows JavaScript Devs to Program Embedded Devices – The New Stack

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Toolkit Allows JavaScript Devs to Program Embedded Devices  The New Stack Source link

Read more

Select data value from grandparent div? – JavaScript – SitePoint

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Select data value from grandparent div? - JavaScript  SitePoint Source link

Read more

How to Handle Errors in JavaScript – Programming – MUO – MakeUseOf

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

How to Handle Errors in JavaScript - Programming  MUO - MakeUseOf Source link

Read more

How to Use the Javascript Slice Method – hackernoon.com

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

How to Use the Javascript Slice Method  hackernoon.com Source link

Read more

Clean Code in JavaScript – SitePoint

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Clean Code in JavaScript  SitePoint Source link

Read more
Next Post
Improve Matplotlib With Style Sheets & Python Async for the Web – The Real Python Podcast

Improve Matplotlib With Style Sheets & Python Async for the Web – The Real Python Podcast

Leave a Reply Cancel reply

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

Related News

A quick glance at the history of C programming languages

A quick glance at the history of C programming languages

November 5, 2022
Sothink JavaScript Web Scroller Crack Free √

Sothink JavaScript Web Scroller Crack Free √

December 12, 2022
SEO poisoning campaign directs search engine visitors from multiple industries to JavaScript malware

SEO poisoning campaign directs search engine visitors from multiple industries to JavaScript malware

September 24, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • Java Developer Survey Reveals Increased Need for Java … – PR Newswire
  • What You Should Definitely Pay Attention to When Hiring Java Developers – Modern Diplomacy
  • Java Web Frameworks Software Market Research Report 2023 … – Los Alamos Monitor

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?