前端截图神器,弃用 html2canvas,SnapDOM超快截图神器

弃用 html2canvas,SnapDOM超快截图神器

在前端开发中,网页截图是个常用功能。从前,html2canvas 是大家的常客,但随着网页越来越复杂,它的性能问题也逐渐暴露,速度慢、占资源,用户体验不尽如人意。好在,现在有了 SnapDOM,一款性能超棒、还原度超高的截图新秀,能完美替代 html2canvas,让截图不再是麻烦事。


在这里插入图片描述

SnapDOM 优势

  • 快得飞起
    测试数据显示,在不同场景下,SnapDOM 都把 html2canvas 和 dom-to-image 这俩老前辈远远甩在身后。
    尤其在超大元素(4000×2000)截图时,速度是 html2canvas 的 93.31 倍,比 dom-to-image 快了 133.12 倍。这速度,简直就像坐火箭。

  • 还原度超高
    SnapDOM 截图出来的效果,跟在网页上看到的一模一样。
    各种复杂的 CSS 样式、伪元素、Shadow DOM、内嵌字体、背景图片,还有动态效果的当前状态,都能精准还原。
    无论是简单的元素,还是复杂的网页布局,它都能轻松拿捏。

  • 格式任你选
    不管你是想要矢量图 SVG,还是常用的 PNG、JPG,或者现代化的 WebP,又或者是需要进一步处理的 Canvas 元素,SnapDOM 都能满足你。

  • 和其他库比咋样
    在这里插入图片描述

用的时候注意点

用 SnapDOM 时,有几点得注意:

跨域资源
要是截图里有外部图片等跨域资源,得确保这些资源支持 CORS,不然截不出来。

iframe 限制
SnapDOM 不能截 iframe 内容,这是浏览器的安全限制,没办法。

Safari 浏览器兼容性
在 Safari 里用 WebP 格式时,会自动变成 PNG。

大型页面截图
截超大页面时,建议分块截,不然可能会内存溢出。

在这里插入图片描述



snapDOM README

在这里插入图片描述

在这里插入图片描述

snapDOM is a fast and accurate DOM-to-image capture tool built for Zumly, a zoom-based view transition framework.

It captures any HTML element as a scalable SVG image, preserving styles, fonts, background images, pseudo-elements, and even shadow DOM. It also supports export to raster image formats and canvas.

  • 📸 Full DOM capture
  • 🎨 Embedded styles, pseudo-elements, and fonts
  • 🖼️ Export to SVG, PNG, JPG, WebP, or canvas
  • ⚡ Ultra fast, no dependencies
  • 📦 100% based on standard Web APIs

Demo

https://zumerlab.github.io/snapdom/

Installation

NPM / Yarn

npm i @zumer/snapdom
yarn add @zumer/snapdom

CDN

<script src="https://cdn.jsdelivr.net/npm/@zumer/snapdom/dist/snapdom.min.js"></script>

Script tag (local)

<script src="snapdom.js"></script>

ES Module

import { snapdom } from './snapdom.mjs';

Module via CDN

<script type="module">
  import { snapdom } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom/dist/snapdom.mjs';
</script>

Basic usage

Reusable capture

const el = document.querySelector('#target');
const result = await snapdom(el, { scale: 2 });

const img = await result.toPng();
document.body.appendChild(img);

await result.download({ format: 'jpg', filename: 'my-capture' });

One-step shortcuts

const el = document.querySelector('#target');
const png = await snapdom.toPng(el);
document.body.appendChild(png);

const blob = await snapdom.toBlob(el);

API

snapdom(el, options?)

Returns an object with reusable export methods:

{
  url: string;
  toRaw(): string;
  toImg(): Promise<HTMLImageElement>;
  toCanvas(): Promise<HTMLCanvasElement>;
  toBlob(): Promise<Blob>;
  toPng(): Promise<HTMLImageElement>;
  toJpg(options?): Promise<HTMLImageElement>;
  toWebp(options?): Promise<HTMLImageElement>;
  download(options?): Promise<void>;
}

Shortcut methods

MethodDescription
snapdom.toImg(el, options?)Returns an HTMLImageElement
snapdom.toCanvas(el, options?) Returns a Canvas
snapdom.toBlob(el, options?)Returns an SVG Blob
snapdom.toPng(el, options?)Returns a PNG image
snapdom.toJpg(el, options?)Returns a JPG image
snapdom.toWebp(el, options?)Returns a WebP image
snapdom.download(el, options?) Triggers download in specified format

Options

All capture methods accept an options object:

OptionTypeDefaultDescription
compressbooleantrueRemoves redundant styles
fastbooleantrueSkips idle delay for faster results
embedFontsbooleanfalseInlines fonts (icon fonts always embedded)
scalenumber1Output scale multiplier
widthnumber-Output specific width size
heightnumber-Output specific height size
backgroundColorstring"#fff"Fallback color for JPG/WebP
qualitynumber1Quality for JPG/WebP (0 to 1)
crossOriginfunction-Function to determine CORS mode per image URL

Setting custom dimensions with width and height options

Use the width and height options to generate an image with specific dimensions.

Examples:

1. Fixed width (proportional height)
Sets a specific width while maintaining the aspect ratio. Height adjusts proportionally.

const result = await snapdom(element, {
  width: 400 // Outputs a 400px-wide image with auto-scaled height
});

2. Fixed height (proportional width)
Sets a specific height while maintaining the aspect ratio. Width adjusts proportionally.

const result = await snapdom(element, {
  height: 200 // Outputs a 200px-tall image with auto-scaled width
});

3. Fixed width and height (may distort image)
Forces exact dimensions, potentially distorting the image if the aspect ratio differs.

const result = await snapdom(element, {
  width: 800,  // Outputs an 800px × 200px image (may stretch/squish content)
  height: 200  
});

Note: If scale is different from 1, it takes priority over width and height.
Example: { scale: 3, width: 500 } ignores width and scales the image 3x instead.

Cross-Origin Images

By default, snapDOM loads images with crossOrigin="anonymous". You can customize this behavior using the crossOrigin option:

const result = await snapdom(element, {
  crossOrigin: (url) => {
    // Use credentials for same-origin images
    if (url.startsWith(window.location.origin)) {
      return "use-credentials";
    }
    // Use anonymous for cross-origin images
    return "anonymous";
  }
});

This is useful when your images require authentication or when dealing with credentialed requests.

Download options

{
  format?: "svg" | "png" | "jpg" | "jpeg" | "webp"; // default: "png"
  filename?: string;         // default: "capture"
  backgroundColor?: string;  // optional override
}

preCache() – Optional helper

The preCache() function can be used to load external resources (like images and fonts) in advance. It is specially useful when the element to capure is big and complex.

import { preCache } from '@zumer/snapdom';

await preCache(document.body);
import { snapdom, preCache } from './snapdom.mjs';
    window.addEventListener('load', async () => {
    await preCache();
    console.log('📦 Resources preloaded');
    });

Options for preCache():

  • embedFonts (boolean, default: true) — Inlines non-icon fonts during preload.
  • reset (boolean, default: false) — Clears all existing internal caches.
  • crossOrigin (function) — Function to determine CORS mode per image URL during preload.

Features

  • Captures shadow DOM and Web Components
  • Supports ::before, ::after and ::first-letter pseudo-elements
  • Inlines background images and fonts
  • Handles Font Awesome, Material Icons, and more
  • data-capture="exclude" to ignore an element
  • data-capture="placeholder" with data-placeholder-text for masked replacements

Limitations

  • External images must be CORS-accessible (use crossOrigin option for credentialed requests)
  • Iframes are not supported
  • When WebP format is used on Safari, it will fallback to PNG rendering.
  • @font-face CSS rule is well supported, but if need to use JS FontFace(), see this workaround #43

Benchmarks

snapDOM is not only highly accurate — it’s extremely fast.

Latest benchmarks show significant performance improvements against other libraries:

Scenariovs. modern-screenshotvs. html2canvas
Small element (200×100)6.46× faster32.27× faster
Modal size (400×300)7.28× faster32.66× faster
Page view (1200×800)13.17× faster35.29× faster
Large scroll area (2000×1500)38.23× faster68.85× faster
Very large element (4000×2000)93.31× faster133.12× faster
Complex small element (200×100)3.97× faster15.23× faster
Complex modal (400×300)2.32× faster5.33× faster
Complex page (1200×800)1.62× faster1.65× faster
Complex large scroll (2000×1500)1.66× faster1.24× faster
Complex very large (4000×2000)1.52× faster1.28× faster

Run the benchmarks

To run these benchmarks yourself:

git clone https://github.com/zumerlab/snapdom.git
cd snapdom
npm install
npm run test:benchmark

They execute in headless Chromium using real DOM nodes.

Development

To contribute or build snapDOM locally:

# Clone the repository
git clone https://github.com/zumerlab/snapdom.git
cd snapdom

# Install dependencies
npm install

# Compile the library (ESM, CJS, and minified versions)
npm run compile

# Run tests
npm test

# Run Benchmarks
npm run test:benchmark
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜空孤狼啸

你的鼓励是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值