html2canvas

1.4.1 · active · verified Sun Apr 19

html2canvas is a client-side JavaScript library, currently at stable version 1.4.1, designed to take "screenshots" of webpages or specific DOM elements directly within the user's browser. It operates by reading the Document Object Model (DOM) and applied CSS styles to construct a canvas image, entirely on the client-side, without requiring server-side rendering. A key differentiator is its complete client-side operation, making it suitable for browser-only screenshot needs like generating certificates or tickets. However, it's important to note that it produces a DOM-based representation, which might not be 100% pixel-accurate compared to an actual screenshot, and has limitations regarding unsupported CSS properties. The project maintains a fairly active release cadence, but the README explicitly warns that it is in a "very experimental state" and not recommended for production use, implying potential instability or breaking changes. It is explicitly not suitable for Node.js environments for rendering and requires a proxy for handling cross-origin content.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import and use html2canvas to capture the entire document body, convert it to an image, and append it to the page. It includes basic options for cross-origin content handling and logging.

import html2canvas from 'html2canvas';

const captureAndDisplayBody = async () => {
  const bodyElement = document.body;

  try {
    const canvas = await html2canvas(bodyElement, {
      allowTaint: true, // Set to true if you are handling tainted canvases (e.g., cross-origin images without proxy)
      useCORS: true,    // Attempt to load images using CORS
      logging: true     // Enable logging for debugging
    });

    // Create an image element from the canvas
    const img = document.createElement('img');
    img.src = canvas.toDataURL('image/png');
    img.alt = 'Screenshot of the page body';
    img.style.maxWidth = '100%';
    img.style.border = '2px solid blue';
    
    // Append the image to the document or a specific container
    document.getElementById('screenshot-container')?.appendChild(img);
    console.log('Screenshot captured and displayed successfully!');

  } catch (error) {
    console.error('Error capturing screenshot:', error);
  }
};

// Example of triggering the capture (e.g., on a button click or after DOM load)
document.addEventListener('DOMContentLoaded', () => {
  const button = document.createElement('button');
  button.textContent = 'Take Screenshot of Body';
  button.onclick = captureAndDisplayBody;
  document.body.prepend(button);

  const container = document.createElement('div');
  container.id = 'screenshot-container';
  document.body.appendChild(container);
});

view raw JSON →