HTML-to-Image Conversion with JavaScript
Converting parts of a webpage into downloadable images is a common requirement in dashboards, reporting tools, visual editors, and apps that generate shareable content. JavaScript provides several ways to capture HTML and turn it into PNG, JPEG, or SVG files. This guide covers practical techniques using html2canvas, dom-to-image, and a lightweight SVG-to-canvas approach.
The goal is to help you understand how these tools work, how to implement them, and how to avoid common pitfalls such as CORS issues, font loading, and rendering inconsistencies.
Method 1: Using html2canvas
html2canvas reads the DOM, applies computed styles, and renders a pixel-perfect representation onto a <canvas> element. It works well for most layouts.
Usage
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>HTML
<div id="capture" style="padding: 10px; background: #f5da55">
<h4>Convert this content</h4>
<p>Hello World!</p>
</div>
<button onclick="exportToImage()">Generate Image</button>JavaScript
<script>
async function exportToImage() {
const element = document.getElementById("capture");
try {
const canvas = await html2canvas(element, {
allowTaint: true,
useCORS: true,
scale: 2,
});
const url = canvas.toDataURL("image/png");
const link = document.createElement("a");
link.download = "screenshot.png";
link.href = url;
link.click();
} catch (err) {
console.error("Conversion error:", err);
}
}
</script>Strengths
- Easy to implement
- Good general-purpose conversion
- Supports high-resolution output via
scale
Limitations
- May struggle with complex shadows, filters, or iframes
- Dependent on CORS for remote images
Method 2: Using dom-to-image
dom-to-image works differently—it serializes HTML into SVG and renders it to image formats. This sometimes results in cleaner edges and sharper exports.
Usage
<script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>JavaScript
const element = document.getElementById("capture");
// PNG export
domtoimage.toPng(element).then(url => {
const img = new Image();
img.src = url;
document.body.appendChild(img);
});
// JPEG export
domtoimage.toJpeg(element, { quality: 0.95 }).then(url => {
/* handle JPEG */
});
// SVG export
domtoimage.toSvg(element).then(svg => {
/* handle SVG */
});Strengths
- Great for vector-like crispness
- Supports multiple output formats
- Often produces cleaner results than html2canvas
Limitations
- CSS parsing may differ from browser rendering
- Some styles (filters, blend modes) are ignored
Important Considerations
1. CORS Issues With External Images
Browsers block rendering of remote images unless the server allows:
Access-Control-Allow-Origin: *To minimize issues:
- Prefer local hosting of assets
- Use
{ useCORS: true }in html2canvas - Ensure images include
crossorigin="anonymous"
2. CSS Rendering Differences
- Shadows and filters may be simplified
-
position: fixedelements can shift - Complex gradients may rasterize poorly
3. Performance Tips
- Use
scale: 2orwindow.devicePixelRatiofor high-DPI displays - Reduce heavy box shadows and large images
- Avoid capturing huge DOM nodes at once
4. Font Loading
If custom fonts are not loaded in time, the capture will fallback to system fonts.
Use FontFaceObserver if needed:
await new FontFaceObserver("Inter").load();Alternative: SVG + Canvas (No External Libraries)
This technique embeds the HTML inside an SVG <foreignObject> and converts it into an image. It is minimal but more limited.
const html = document.getElementById("content").innerHTML;
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">${html}</div>
</foreignObject>
</svg>
`;
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);Useful for simple markup, but expect strict limitations:
- External CSS may not apply
- Remote images won’t load
- Layout differences are common
Choosing the Right Method
| Requirement | Best Option |
|---|---|
| Simple screenshots | html2canvas |
| High-quality vector-like output | dom-to-image (SVG mode) |
| Offline / no libraries | SVG + Canvas |
| Remote resources | Ensure CORS support |
Conclusion
HTML-to-image conversion is a practical technique for many interfaces—from generating shareable cards to exporting dashboard widgets or saving custom content.
- html2canvas works well for most layouts.
- dom-to-image is ideal when you need sharp SVG-based output.
- SVG+Canvas can be useful for small controlled components.
By understanding how each method handles styles, fonts, and remote assets, you can choose the best approach and avoid common pitfalls.