html2canvas-pro

yorickshanMIT活跃维护

用 JavaScript 把网页 DOM 直接渲染成图片,是 html2canvas 的升级版,支持更多现代 CSS 特性,适合前端做页面截图和导出。

Screenshots with JavaScript. Next generation!

v2.6.3发布于 2026-11-05 05:49 UTC589star +1 / 7 天52fork同步于 2026-11-10 17:58 UTC

怎么上手

由 README 提炼,执行前请确认
npm install html2canvas-pro
硬件要求按 README 说明

纯浏览器端 JavaScript 库,README 未说明显存或 GPU 要求;构建与测试需 Node.js 24,运行时 dist 包不依赖 Node 版本

支持 Apple Silicon
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

html2canvas 的增强分支,用 JavaScript 把 DOM 截成 canvas,支持现代 CSS

用 JavaScript 把网页 DOM 直接渲染成图片,是 html2canvas 的升级版,支持更多现代 CSS 特性,适合前端做页面截图和导出。

核心能力

  • 支持 oklch、lab、color 等现代颜色函数
  • 支持 background-clip:text、mix-blend-mode、clip-path
  • 支持 mask-image、backdrop-filter 毛玻璃与 conic-gradient
  • 内置 Validator 做 XSS/SSRF 输入校验
  • 提供 onProgress、onError 与 AbortSignal 取消钩子

容易踩的坑

默认输出尺寸受 devicePixelRatio 影响,要精确像素需显式设 width、height 并 scale:1;跨域图片需开启 useCORS 或配置代理,否则 canvas 会被污染;包内 engines 声明 node>=24,仅影响从源码构建测试,不影响运行时

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v2.6.3
  1. v2.6.3最新正式版2026-11-05 · 2026-11-05 05:49 UTC

    Please refer to CHANGELOG.md for details.

  2. v2.6.22026-11-04 · 2026-11-04 13:20 UTC
    查看更新说明

    Please refer to CHANGELOG.md for details.

  3. v2.6.12026-11-04 · 2026-11-04 02:57 UTC
    查看更新说明

    Please refer to CHANGELOG.md for details.

  4. v2.6.02026-10-30 · 2026-10-30 07:23 UTC
    查看更新说明

    Please refer to CHANGELOG.md for details.

  5. v2.5.32026-10-29 · 2026-10-29 09:52 UTC
    查看更新说明

    Please refer to CHANGELOG.md for details.

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Why html2canvas-pro?

    html2canvas-pro is a fork of niklasvh/html2canvas that includes various fixes and new features. It offers several advantages over the original html2canvas:

    Modern CSS support

    • Color functions color() (incl. relative colors), lab(), lch(), oklab(), oklch() — other functions resolve through the browser's computed styles
    • background-clip: text support
    • mix-blend-mode and background-blend-mode support
    • object-fit support for <img/>
    • CSS clip-path support (inset, rect, xywh, circle, ellipse, polygon, path)
    • CSS writing-mode support (horizontal-tb, vertical-rl, vertical-lr)
    • mask-image alpha masks with position/size/repeat (see mask support)
    • backdrop-filter: blur() for frosted-glass captures (see backdrop-filter support)
    • conic-gradient(), repeating-conic-gradient() and repeating-radial-gradient() — complete gradient family
    • text-emphasis (CJK emphasis marks), -webkit-box-reflect, image-set(), border-image-outset / border-image-width
    • accent-color, outline, -webkit-text-fill-color, isolation
    • filter chain compositing for eligible layers — the full standard filter function set rendered on a dedicated surface with correct layer opacity (see filter support notes)
    • Faithful box-shadow rendering, including inset shadows, blur scaling, and shadows through transformed ancestors
    • image-rendering CSS property plus imageSmoothing / imageSmoothingQuality options for pixel-perfect output
    • Border image, counters & quotes, direction, line-height, transform-origin, and more — see the full feature list

    Developer experience

    • Security validation — Built-in input validation (Validator API, XSS/SSRF protection)
    • Performance monitoring — Built-in PerformanceMonitor with per-phase timings
    • Error, progress & cancellation hooks — onError for failed resources, onProgress for pipeline milestones (incl. per-batch image preload progress), AbortSignal cancellation
    • TypeScript — First-class type definitions included
    • Shadow DOM & Web Components — slot assignment, shadow-root cloning, and automatic iframe placement

    Performance

    • Deferred (batched, parallel) image preloading
    • LRU caches for CSS parsing and gradient patterns
    • Native canvas filter fast path with verified SVG fallback

    Render speed — html2canvas-pro(latest) vs html2canvas 1.4.1, headless Chromium on Apple M4, scale: 1, median of 10 interleaved runs (benchmark script, reproduce with corepack pnpm bench:render):

    Fixturehtml2canvas-prohtml2canvas 1.4.1
    Simple document (~40 elements)80 ms87 ms
    Large document (~1200 elements)295 ms468 ms
    Modern-CSS page (oklch(), conic-gradient(), …)166 ms✗ cannot render (throws on oklch())

    On element-heavy pages html2canvas-pro is ~1.6× faster, and it is the only one of the two that can render modern-CSS content at all. Absolute times vary by machine — compare ratios, not milliseconds.

    If you found this helpful, don't forget to leave a star 🌟.

    Installation

    npm install html2canvas-pro
    pnpm add html2canvas-pro
    yarn add html2canvas-pro
    

    Note on the engines field: the published package declares engines: { node: ">=24" }. That constraint applies to building and testing the library from a checkout (the test toolchain needs Node 24) — the dist/ bundles are plain browser JavaScript with no Node dependency, so consuming the package at runtime is unaffected on any Node version.

    Usage

    import html2canvas from 'html2canvas-pro';
    

    To render an element with html2canvas-pro with some (optional) options, simply call html2canvas(element, options);

    Basic Example

    html2canvas(document.body).then(function(canvas) {
        document.body.appendChild(canvas);
    });
    

    Script tag / CDN

    A browser bundle is also available (exposes the global window.html2canvas):

    <script src="https://cdn.jsdelivr.net/npm/html2canvas-pro/dist/html2canvas-pro.min.js"></script>
    <script>
      html2canvas(document.body).then((canvas) => document.body.appendChild(canvas));
    </script>
    

    Controlling Output Dimensions

    ⚠️ Important: By default, the output canvas dimensions are affected by devicePixelRatio.

    // If you need exact pixel dimensions (e.g., for a specific file size):
    html2canvas(element, {
        width: 1920,
        height: 1080,
        scale: 1  // Set scale to 1 for exact dimensions
    }).then(canvas => {
        // Canvas will be exactly 1920×1080 pixels
        const dataURL = canvas.toDataURL('image/png');
    });
    

    See the Configuration Guide for more details.

    Error Handling & Cancellation

    const controller = new AbortController();
    
    html2canvas(element, {
        useCORS: true,
        onError: (error) => {
            // Called when a resource (image, font, …) fails to load.
            // The render continues — this is a notification hook, not an abort.
            console.warn('Resource failed:', error);
        },
        signal: controller.signal // Rejects with an AbortError when aborted
    }).then(canvas => {
        document.body.appendChild(canvas);
    });
    
    // Cancel an in-progress capture:
    controller.abort();
    

    Pixel-Perfect Capture

    html2canvas(element, {
        imageSmoothing: false,       // Disable anti-aliasing globally
        scale: 2                     // Upscale without blur
    });
    // Or per-element via CSS: style="image-rendering: pixelated"
    

    API

    The package exports html2canvas (default), plus the following named exports:

    ExportDescription
    html2canvasRender an element to a <canvas>
    Html2CanvasConfigPer-call runtime config (CSP nonce, shared cache)
    Validator / createDefaultValidatorInput validation (URLs, proxy allow-list, element checks)
    PerformanceMonitorPhase-level timing metrics
    OptionsThe full options type
    ConfigOptionsPer-call runtime config type (CSP nonce, shared cache)
    ValidationResultResult type returned by the Validator API

    Full type definitions ship with the package — your editor's IntelliSense covers every option. An HTML API reference can be generated locally with corepack pnpm docs:api (TypeDoc).

    Documentation

    The full documentation site lives at yorickshan.github.io/html2canvas-pro:

    • Getting Started — installation, usage, live demo
    • Configuration — every option with defaults and examples
    • Features — supported CSS properties and values
    • Proxy — cross-origin image handling
    • FAQ — canvas size, tainted canvas, browser limits
    • Architecture — how the rendering pipeline works

    Development

    The project uses pnpm (the version is pinned via the packageManager field — Corepack handles it automatically). Unit tests require Node.js 24 (jsdom 30).

    corepack pnpm install
    corepack pnpm build          # tsc + Rolldown bundles (CJS/ESM/UMD)
    corepack pnpm unittest       # Vitest unit tests
    corepack pnpm test           # lint + unit tests + browser reftests (Playwright)
    corepack pnpm docs:dev       # VitePress dev server
    corepack pnpm docs:api       # Generate the TypeDoc API reference
    

    See CONTRIBUTING.md for the full guide, including how to add a new CSS property.

    Contribution

    If you'd like to add a feature, feel free to submit a PR.

    Interested in becoming a maintainer? Open an issue or reach out to @yorickshan.

    License

    MIT