html2canvas-pro

repository·main·Indexed 19 days ago

https://github.com/yorickshan/html2canvas-pro

A next-generation JavaScript screenshot tool and feature-rich fork of html2canvas used to render DOM elements into a canvas. It offers improved CSS support for object-fit, clip-path, and writing-mode, advanced color functions (lab, lch, oklab, oklch), built-in XSS/SSRF protection, and a performance measurement API. The library reconstructs a visual representation of the DOM by parsing CSS properties through a five-phase pipeline: DOM cloning, CSS parsing, layout, stacking context, and canvas rendering.

Tokens
17.2K
Snippets
44
Records
66
Agent score
68%

What's inside html2canvas-pro

  1. What makes html2canvas-pro different from html2canvas?

    main

    html2canvas-pro is a fork of niklasvh/html2canvas that includes several advanced features and fixes:

    • Advanced Color Support: Includes color() (including relative colors) and lab() / lch() / oklab() / oklch() functions.
    • CSS Support: Support for object-fit on <img> elements, clip-path (inset, circle, ellipse, polygon, path), and writing-mode (horizontal-tb, vertical-rl, vertical-lr).
    • Image Rendering: Control over image smoothing via the CSS image-rendering property and imageSmoothing/imageSmoothingQuality options.
    • Security: Built-in input validation for XSS/SSRF protection.
    • Monitoring: Built-in performance measurement API.
  2. Capabilities of html2canvas-pro compared to html2canvas

    main

    Compared to the original html2canvas, html2canvas-pro provides enhanced support for modern CSS features and improved developer tooling. Key improvements include:

    Color Function Support

    Supports advanced CSS color functions:

    • color() (including relative colors)
    • lab()
    • lch()
    • oklab()
    • oklch()

    Layout & Rendering Enhancements

    • clip-path: Supports inset(), circle(), ellipse(), polygon(), and path().
    • object-fit: Full support for the object-fit property on <img> elements.
    • writing-mode: Supports horizontal-tb, vertical-rl, and vertical-lr.
    • Image Smoothing: Supports the CSS image-rendering property, as well as imageSmoothing and imageSmoothingQuality configuration options.

    Developer Experience & Security

    • Security: Includes a built-in Validator API to protect against XSS and SSRF.
    • Performance: Includes a built-in PerformanceMonitor API for collecting metrics.
    • Typing: Provides first-class TypeScript definitions.
    • Testing: Uses Vitest for modern, fast testing.
  3. Understand the limitations of html2canvas-pro

    main

    When using html2canvas-pro, be aware of the following constraints:

    • CSS Support: Only CSS properties understood by the script will be rendered correctly.
    • Cross-Origin Images: All images used must reside within the same origin to be read without using a proxy.
    • Tainted Canvases: Any canvas elements on the page that have been tainted with cross-origin content will become "dirty" and cannot be read by the script.
    • Plugin Content: The script cannot render content from plugins such as Flash or Java applets.
  4. How the html2canvas-pro rendering pipeline works

    main

    html2canvas-pro follows a five-phase pipeline to transform a live DOM element into a visual <canvas> representation:

    1. DOM Cloning: The source DOM is deep-cloned into a hidden <iframe> using DocumentCloner. This ensures getComputedStyle returns resolved values and prevents cross-origin taint. SlotCloner handles Shadow DOM and <slot> assignments.
    2. CSS Parsing: Raw CSS is tokenized via a state-machine-based Tokenizer and then parsed into CSSValue[] by the Parser. Properties are processed using specific property-descriptors.
    3. Layout: The Bounds class calculates dimensions and positions, while text.ts handles text measurement and line breaking.
    4. Stacking Context: The engine builds a StackingContext tree following the CSS Positioned Layout Module Level 3 painting order (e.g., handling z-index, opacity, and transforms).
    5. Canvas Rendering: CanvasRenderer.render(element) orchestrates the final pass, drawing backgrounds, borders, and content (images, forms, etc.) onto the canvas.
    DOM Clone → CSS Parse → Layout → Stacking Context → Canvas Render
  5. Calculate Canvas Dimensions using width, height, and scale

    main

    Understanding the relationship between CSS dimensions and internal resolution is critical for controlling output quality and size.

    • Canvas Display Size = width × height (CSS pixels, how it appears on screen).
    • Canvas Internal Resolution = (width × scale) × (height × scale) (actual pixels stored in canvas).

    To get an exact pixel dimension (e.g., 1920x1080) without scaling artifacts, set scale: 1.

    // This configuration:
    html2canvas(element, {
        width: 1920,
        height: 1080
    });
    
    // On a device with devicePixelRatio = 2 (e.g., Retina display):
    // Will produce a canvas with:
    // - Display size: 1920px × 1080px
    // - Internal resolution: 3840px × 2160px (1920×2, 1080×2)
    // - Canvas attributes: width="3840" height="2160"
    // - Canvas style: width: 1920px; height: 1080px;
  6. Override same-origin detection with customIsSameOrigin

    main

    The customIsSameOrigin option allows you to override default logic for handling redirects, CDNs, or forcing CORS mode. It accepts a function: (src: string, oldFn: (src: string) => boolean) => boolean | Promise<boolean>.

    Scenarios:

    1. Handling redirects: Check if a URL redirects to an external domain.
    2. CDN configurations: Allow multiple domains.
    3. Force CORS: Always return false to force CORS mode.
    // Basic Usage (Synchronous)
    html2canvas(element, {
        useCORS: true,
        customIsSameOrigin: (src, oldFn) => {
            if (!oldFn(src)) {
                return false;
            }
            const targetUrl = new URL(src);
            const pathname = targetUrl.pathname;
            return !pathname.startsWith('/some-redirect-prefix');
        },
    });
    
    // Async Validation
    html2canvas(element, {
        useCORS: true,
        customIsSameOrigin: async (src, oldFn) => {
            const response = await fetch('/api/check-redirect?url=' + encodeURIComponent(src));
            const data = await response.json();
            return !data.willRedirect;
        },
    });
    
    // Force All Images to Use CORS
    html2canvas(element, {
        useCORS: true,
        customIsSameOrigin: (src, oldFn) => false,
    });
  7. How the Stacking Context and Effects are handled

    main

    To ensure visual fidelity, html2canvas-pro builds a StackingContext tree using parseStackingContexts(element). This tree follows the CSS painting order, ensuring elements with different z-index, opacity, or transform values are rendered in the correct sequence.

    Each ElementPaint node in the tree contains an array of IElementEffect objects, which represent visual modifications applied during the render pass:

    • TransformEffect: Matrix transforms with origin offsets.
    • ClipEffect: Clipping via paths (e.g., overflow or border-radius).
    • OpacityEffect: Global alpha multiplication.
    • ClipPathEffect: CSS clip-path shapes.
    • BlendEffect: mix-blend-mode composite operations.
    • FilterEffect: CSS filter functions.

    The effects-renderer.ts manages these by using ctx.save() and ctx.restore() pairs to ensure effects are correctly nested and do not bleed into subsequent render operations.

  8. Understanding and controlling canvas output dimensions

    main

    The width and height options in html2canvas set the CSS display size, not the internal pixel resolution. By default, the internal resolution is scaled by window.devicePixelRatio to ensure high-quality images on Retina/high-DPI displays.

    The Formula: Canvas pixel width = width × scale
    Canvas pixel height = height × scale

    If you need the output canvas to match your specified width and height exactly (e.g., for predictable file sizes or specific pixel-perfect requirements), you must set scale: 1.

    // On a Retina display (devicePixelRatio = 2):
    html2canvas(element, {
        width: 1920,
        height: 1080
    });
    
    // Results in:
    // - Canvas CSS display size: 1920px × 1080px
    // - Canvas internal resolution: 3840px × 2160px
    // - Canvas HTML: <canvas width="3840" height="2160" style="width: 1920px; height: 1080px;">
  9. Backward Compatibility and Migration for html2canvas-pro

    main

    As of v2.1.0, several global configuration methods have been removed in favor of per-call options.

    Removed Global Config

    • html2canvas.setCspNonce(nonce) is removed.
    • setDefaultConfig and getDefaultConfig are removed.

    New Configuration Pattern

    Instead of setting global state, pass configuration directly via the Options object in your function call. Use a Html2CanvasConfig instance per call to manage settings.

    Supported Input and Types

    • Element input: Accepts HTMLElement or any object containing ownerDocument and ownerDocument.defaultView (useful for mocks or cross-realm references). The element must be attached to a document and window.
    • Numeric options: Options like scale, width, height, imageTimeout, x, y, windowWidth, windowHeight, scrollX, and scrollY accept both numbers and string numbers (which are coerced).
    • DOM normalization: normalizeDom defaults to true. This disables animations and resets transforms during capture. Set normalizeDom: false if you must preserve the original DOM state during the capture process.
  10. CSS rendering limitations

    main
    Because every CSS property must be manually implemented for rendering, html2canvas-pro does not have full CSS support. It aims to support the most commonly used properties. If a property renders incorrectly or is missing, it is a limitation of the library's current implementation.
  11. Use a proxy to bypass CORS and canvas tainting

    main

    By default, html2canvas-pro cannot bypass browser content policy restrictions. When you attempt to draw images from an origin different from your current page, the canvas becomes 'tainted'. Once a canvas is tainted, its contents can no longer be read (e.g., for exporting as an image).

    To load and render images that reside outside of your page's origin, you must use a proxy to route the image requests through a server that adds the necessary CORS headers.

  12. How html2canvas-pro works

    main

    The script captures "screenshots" of web pages or specific DOM elements directly in the user's browser. It does not perform a pixel-level screen capture. Instead, it traverses the DOM, gathers information from every element, and reconstructs a visual representation by reading the CSS properties found in the DOM.

    Because it reconstructs the page rather than capturing pixels, it can only render CSS properties that it explicitly understands. For a complete list of supported styles, refer to the supported features documentation.