JavaScript Development Space

HTML-to-Image Conversion with JavaScript

Converting HTML elements into images is a common requirement for tasks like generating screenshots, sharing webpage content, or saving visual data. In JavaScript, two popular libraries — html2canvas and dom-to-image offer effective solutions. This guide explores both methods, their advantages, and implementation details.

Method 1: Using html2canvas

How It Works

html2canvas traverses the DOM structure, captures styles, and renders the content onto a <canvas> element before converting it into an image.

Implementation

Include via CDN:

html
1 <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

HTML Structure:

html
1 <div id="capture" style="padding: 10px; background: #f5da55">
2 <h4>Convert this content</h4>
3 <p>Hello World!</p>
4 </div>
5 <button onclick="exportToImage()">Generate Image</button>

JavaScript Code:

html
1 <script>
2 async function exportToImage() {
3 const element = document.getElementById("capture");
4 try {
5 const canvas = await html2canvas(element, {
6 allowTaint: true,
7 useCORS: true,
8 scale: 2,
9 });
10 const imgUrl = canvas.toDataURL("image/png");
11 const img = new Image();
12 img.src = imgUrl;
13 document.body.appendChild(img);
14
15 // Download Image
16 const link = document.createElement("a");
17 link.download = "screenshot.png";
18 link.href = imgUrl;
19 link.click();
20 } catch (err) {
21 console.error("Error converting HTML to image:", err);
22 }
23 }
24 </script>

Method 2: Using dom-to-image

How It Works

dom-to-image converts HTML elements into PNG, JPEG, or SVG formats using SVG serialization and CSS parsing.

Implementation

Include via CDN:

html
1 <script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>

JavaScript Code:

html
1 <script>
2 const element = document.getElementById("capture");
3
4 // Export to PNG
5 domtoimage.toPng(element)
6 .then(imgUrl => {
7 const img = new Image();
8 img.src = imgUrl;
9 document.body.appendChild(img);
10 })
11 .catch(err => console.error(err));
12
13 // Export to JPEG with quality setting
14 domtoimage.toJpeg(element, { quality: 0.95 })
15 .then(imgUrl => { /* Handle image */ });
16
17 // Export to SVG
18 domtoimage.toSvg(element)
19 .then(svgData => { /* Handle image */ });
20 </script>

Key Considerations

Cross-Domain Resource Issues

  • External images may not be captured unless the server allows CORS (Access-Control-Allow-Origin).
  • Use { useCORS: true } when initializing html2canvas.

CSS Compatibility

  • Some properties like box-shadow and filter may not render accurately.
  • position: fixed elements may be ignored.

Performance Optimization

  • High-resolution exports (scale: 2 or more) improve quality but increase processing time.
  • Consider using window.devicePixelRatio for better adaptation to high-DPI screens.

Font Rendering

  • Ensure custom fonts are fully loaded before conversion (use FontFaceObserver if needed).

Alternative: Using SVG and Canvas

For native implementation without third-party libraries, an SVG foreignObject approach can be used:

html
1 <script>
2 const svgStr = `
3 <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
4 <foreignObject width="100%" height="100%">
5 <div xmlns="http://www.w3.org/1999/xhtml">${document.getElementById("content").innerHTML}</div>
6 </foreignObject>
7 </svg>
8 `;
9 const imgUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgStr)}`;
10 </script>

However, due to browser security restrictions, this method may not support external resources properly.

Choosing the Right Solution

RequirementRecommended Method
General Usehtml2canvas
High-Quality Exportsdom-to-image (SVG)
Cross-Domain ContentEnsure CORS settings

By following these approaches, you can efficiently convert HTML elements into images using JavaScript while handling common pitfalls effectively.

JavaScript Development Space

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.