html2canvas-pro

2.0.2 · active · verified Sun Apr 19

html2canvas-pro is an actively maintained fork of the popular `niklasvh/html2canvas` library, designed to capture screenshots of web pages or specific DOM elements using JavaScript. It is currently at version 2.0.2 and appears to have a consistent release cadence with several recent patch releases following a major version bump to 2.0.0. Key differentiators include enhanced support for modern CSS color functions like `color()`, `lab()`, `lch()`, `oklab()`, and `oklch()`, improved handling of `object-fit` for images, and explicit control over image smoothing via the `image-rendering` CSS property or a global option. This package aims to address various issues and provide advanced features beyond the original `html2canvas` project, making it suitable for complex screenshot requirements where standard `html2canvas` might fall short. It ships with TypeScript types for improved developer experience.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to capture a screenshot of the document body or a specific element, append the generated canvas to the DOM, and control output dimensions and image format.

import html2canvas from 'html2canvas-pro';

// Capture the entire document body and append it to the DOM
html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
    console.log('Screenshot of document body appended.');

    // Get the screenshot as a Data URL
    const dataURL = canvas.toDataURL('image/png');
    console.log('Partial Data URL:', dataURL.substring(0, 50) + '...');
});

// Example: Capture a specific element with controlled dimensions and scale
const elementToCapture = document.createElement('div');
elementToCapture.id = 'target-element';
elementToCapture.style.cssText = 'width: 300px; height: 150px; background-color: #e0f7fa; border: 2px solid #00bcd4; margin-top: 20px; display: flex; align-items: center; justify-content: center; font-family: sans-serif;';
elementToCapture.textContent = 'Capture me!';
document.body.appendChild(elementToCapture);

html2canvas(elementToCapture, {
    width: 600,  // Target output width
    height: 300, // Target output height
    scale: 1,    // Important: set scale to 1 for exact pixel dimensions, ignoring devicePixelRatio
    backgroundColor: null // Set to null for a transparent background if the source has none
}).then(scaledCanvas => {
    const scaledDataURL = scaledCanvas.toDataURL('image/jpeg', 0.8); // Get as JPEG with 80% quality
    console.log('Scaled screenshot data URL length:', scaledDataURL.length);
    // Optionally append the scaled canvas as well
    document.body.appendChild(scaledCanvas);
    scaledCanvas.style.marginTop = '20px';
});

view raw JSON →