snapdom

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SnapDOM Skill

SnapDOM 工具库

Fast, dependency-free DOM-to-image capture library for converting HTML elements into scalable SVG or raster image formats.
这是一款无依赖的快速DOM转图像捕获库,可将HTML元素转换为可缩放的SVG或光栅图像格式。

When to Use This Skill

何时使用本工具库

Use SnapDOM when you need to:
  • Convert HTML elements to images (SVG, PNG, JPG, WebP)
  • Capture styled DOM with pseudo-elements and shadows
  • Export elements with embedded fonts and icons
  • Create screenshots with custom dimensions or scaling
  • Handle CORS-blocked resources using proxy fallback
  • Implement custom rendering pipelines with plugins
  • Optimize performance on large or complex elements
当你需要以下功能时使用SnapDOM:
  • 将HTML元素转换为图像(SVG、PNG、JPG、WebP)
  • 捕获包含伪元素和阴影的样式化DOM
  • 导出包含嵌入字体和图标的元素
  • 创建自定义尺寸或缩放比例的截图
  • 使用代理回退处理CORS拦截的资源
  • 通过插件实现自定义渲染流水线
  • 优化大型或复杂元素的捕获性能

Key Features

核心特性

Universal Export Options

通用导出选项

  • SVG - Scalable vector format, embeds all styles
  • PNG, JPG, WebP - Raster formats with configurable quality
  • Canvas - Get raw Canvas element for further processing
  • Blob - Raw binary data for custom handling
  • SVG - 可缩放矢量格式,嵌入所有样式
  • PNG, JPG, WebP - 可配置质量的光栅格式
  • Canvas - 获取原始Canvas元素以进行后续处理
  • Blob - 用于自定义处理的原始二进制数据

Performance

性能表现

  • Ultra-fast capture (1.6ms for small elements, ~171ms for 4000×2000)
  • No dependencies - Uses standard Web APIs only
  • Outperforms html2canvas by 10-40x on complex elements
  • 超快速捕获(小元素仅需1.6ms,4000×2000元素约171ms)
  • 无依赖 - 仅使用标准Web API
  • 在复杂元素上的性能比html2canvas快10-40倍

Style Support

样式支持

  • Embedded fonts (including icon fonts)
  • CSS pseudo-elements (::before, ::after)
  • CSS counters
  • CSS line-clamp
  • Transform and shadow effects
  • Shadow DOM content
  • 嵌入字体(包括图标字体)
  • CSS伪元素(::before, ::after)
  • CSS计数器
  • CSS line-clamp
  • 变换和阴影效果
  • Shadow DOM内容

Advanced Capabilities

高级功能

  • Same-origin iframe support
  • CORS proxy fallback for blocked assets
  • Plugin system for custom transformations
  • Straighten transforms (remove rotate/translate)
  • Selective element exclusion
  • Tight bounding box calculation
  • 同源iframe支持
  • 针对被拦截资源的CORS代理回退
  • 用于自定义转换的插件系统
  • 拉直变换(移除旋转/平移)
  • 选择性元素排除
  • 精确的边界框计算

Installation

安装

NPM/Yarn

NPM/Yarn

bash
npm install @zumer/snapdom
bash
npm install @zumer/snapdom

or

or

yarn add @zumer/snapdom
undefined
yarn add @zumer/snapdom
undefined

CDN (ES Module)

CDN (ES Module)

html
<script type="module">
  import { snapdom } from "https://unpkg.com/@zumer/snapdom/dist/snapdom.mjs";
</script>
html
<script type="module">
  import { snapdom } from "https://unpkg.com/@zumer/snapdom/dist/snapdom.mjs";
</script>

CDN (UMD)

CDN (UMD)

html
<script src="https://unpkg.com/@zumer/snapdom/dist/snapdom.umd.js"></script>
html
<script src="https://unpkg.com/@zumer/snapdom/dist/snapdom.umd.js"></script>

Quick Start Examples

快速开始示例

Basic Reusable Capture

基础可复用捕获

javascript
// Create reusable capture object
const result = await snapdom(document.querySelector('#target'));

// Export to different formats
const png = await result.toPng();
const jpg = await result.toJpg();
const svg = await result.toSvg();
const canvas = await result.toCanvas();
const blob = await result.toBlob();

// Use the result
document.body.appendChild(png);
javascript
// 创建可复用的捕获对象
const result = await snapdom(document.querySelector('#target'));

// 导出为不同格式
const png = await result.toPng();
const jpg = await result.toJpg();
const svg = await result.toSvg();
const canvas = await result.toCanvas();
const blob = await result.toBlob();

// 使用结果
document.body.appendChild(png);

One-Step Export

一步式导出

javascript
// Direct export without intermediate object
const png = await snapdom.toPng(document.querySelector('#target'));
const svg = await snapdom.toSvg(element);
javascript
// 无需中间对象直接导出
const png = await snapdom.toPng(document.querySelector('#target'));
const svg = await snapdom.toSvg(element);

Download Element

下载元素

javascript
// Automatically download as file
await snapdom.download(element, 'screenshot.png');
await snapdom.download(element, 'image.svg');
javascript
// 自动下载为文件
await snapdom.download(element, 'screenshot.png');
await snapdom.download(element, 'image.svg');

With Options

带配置选项

javascript
const result = await snapdom(element, {
  scale: 2,                    // 2x resolution
  width: 800,                  // Custom width
  height: 600,                 // Custom height
  embedFonts: true,            // Include @font-face
  exclude: '.no-capture',      // Hide elements
  useProxy: true,              // Enable CORS proxy
  straighten: true,            // Remove transforms
  noShadows: false             // Keep shadows
});

const png = await result.toPng({ quality: 0.95 });
javascript
const result = await snapdom(element, {
  scale: 2,                    // 2倍分辨率
  width: 800,                  // 自定义宽度
  height: 600,                 // 自定义高度
  embedFonts: true,            // 包含@font-face
  exclude: '.no-capture',      // 隐藏元素
  useProxy: true,              // 启用CORS代理
  straighten: true,            // 移除变换
  noShadows: false             // 保留阴影
});

const png = await result.toPng({ quality: 0.95 });

Essential Options Reference

关键配置选项参考

OptionTypePurpose
scale
NumberScale output (e.g., 2 for 2x resolution)
width
NumberCustom output width in pixels
height
NumberCustom output height in pixels
embedFonts
BooleanInclude non-icon @font-face rules
useProxy
String|BooleanEnable CORS proxy (URL or true for default)
exclude
StringCSS selector for elements to hide
straighten
BooleanRemove translate/rotate transforms
noShadows
BooleanStrip shadow effects
选项类型用途
scale
数字缩放输出(例如,2表示2倍分辨率)
width
数字自定义输出宽度(像素)
height
数字自定义输出高度(像素)
embedFonts
布尔值包含非图标@font-face规则
useProxy
字符串|布尔值启用CORS代理(URL或true使用默认代理)
exclude
字符串要隐藏元素的CSS选择器
straighten
布尔值移除平移/旋转变换
noShadows
布尔值去除阴影效果

Common Patterns

常见使用模式

Responsive Screenshots

响应式截图

javascript
// Capture at different scales
const mobile = await snapdom.toPng(element, { scale: 1 });
const tablet = await snapdom.toPng(element, { scale: 1.5 });
const desktop = await snapdom.toPng(element, { scale: 2 });
javascript
// 以不同缩放比例捕获
const mobile = await snapdom.toPng(element, { scale: 1 });
const tablet = await snapdom.toPng(element, { scale: 1.5 });
const desktop = await snapdom.toPng(element, { scale: 2 });

Exclude Elements

排除元素

javascript
// Hide specific elements from capture
const png = await snapdom.toPng(element, {
  exclude: '.controls, .watermark, [data-no-capture]'
});
javascript
// 捕获时隐藏特定元素
const png = await snapdom.toPng(element, {
  exclude: '.controls, .watermark, [data-no-capture]'
});

Fixed Dimensions

固定尺寸

javascript
// Capture with specific size
const result = await snapdom(element, {
  width: 1200,
  height: 630  // Standard social media size
});
javascript
// 以特定尺寸捕获
const result = await snapdom(element, {
  width: 1200,
  height: 630  // 标准社交媒体尺寸
});

CORS Handling

CORS处理

javascript
// Fallback for CORS-blocked resources
const png = await snapdom.toPng(element, {
  useProxy: 'https://cors.example.com/?' // Custom proxy
});
javascript
// 针对CORS拦截资源的回退方案
const png = await snapdom.toPng(element, {
  useProxy: 'https://cors.example.com/?' // 自定义代理
});

Plugin System (Beta)

插件系统(测试版)

javascript
// Extend with custom exporters
snapdom.plugins([pluginFactory, { colorOverlay: true }]);

// Hook into lifecycle
defineExports(context) {
  return {
    pdf: async (ctx, opts) => { /* generate PDF */ }
  };
}

// Lifecycle hooks available:
// beforeSnap → beforeClone → afterClone →
// beforeRender → beforeExport → afterExport
javascript
// 使用自定义导出器扩展功能
snapdom.plugins([pluginFactory, { colorOverlay: true }]);

// 钩子到生命周期
defineExports(context) {
  return {
    pdf: async (ctx, opts) => { /* 生成PDF */ }
  };
}

// 可用的生命周期钩子:
// beforeSnap → beforeClone → afterClone →
// beforeRender → beforeExport → afterExport

Performance Comparison

性能对比

SnapDOM significantly outperforms html2canvas:
ScenarioSnapDOMhtml2canvasImprovement
Small (200×100)1.6ms68ms42x faster
Medium (800×600)12ms280ms23x faster
Large (4000×2000)171ms1,800ms10x faster
SnapDOM的性能显著优于html2canvas:
场景SnapDOMhtml2canvas提升幅度
小型元素(200×100)1.6ms68ms快42倍
中型元素(800×600)12ms280ms快23倍
大型元素(4000×2000)171ms1,800ms快10倍

Development

开发指南

Setup

环境搭建

bash
git clone https://github.com/zumerlab/snapdom.git
cd snapdom
npm install
bash
git clone https://github.com/zumerlab/snapdom.git
cd snapdom
npm install

Build

构建

bash
npm run compile
bash
npm run compile

Testing

测试

bash
npm test
bash
npm test

Browser Support

浏览器支持

  • Chrome/Edge 90+
  • Firefox 88+
  • Safari 14+
  • Mobile browsers (iOS Safari 14+, Chrome Mobile)
  • Chrome/Edge 90+
  • Firefox 88+
  • Safari 14+
  • 移动浏览器(iOS Safari 14+, Chrome Mobile)

Resources

资源

Documentation

文档

scripts/

scripts/

Add helper scripts here for automation, e.g.:
  • batch-screenshot.js
    - Capture multiple elements
  • pdf-export.js
    - Convert snapshots to PDF
  • compare-outputs.js
    - Compare SVG vs PNG quality
在此处添加自动化辅助脚本,例如:
  • batch-screenshot.js
    - 捕获多个元素
  • pdf-export.js
    - 将快照转换为PDF
  • compare-outputs.js
    - 对比SVG与PNG的质量

assets/

assets/

Add templates and examples:
  • HTML templates for common capture scenarios
  • CSS frameworks pre-configured with snapdom
  • Boilerplate projects integrating snapdom
添加模板和示例:
  • 常见捕获场景的HTML模板
  • 预配置snapdom的CSS框架
  • 集成snapdom的样板项目

Related Tools

相关工具

Tips & Best Practices

技巧与最佳实践

  1. Performance: Use
    scale
    instead of
    width
    /
    height
    for better performance
  2. Fonts: Set
    embedFonts: true
    to ensure custom fonts appear correctly
  3. CORS Issues: Use
    useProxy: true
    if images fail to load
  4. Large Elements: Break into smaller chunks for complex pages
  5. Quality: For PNG/JPG, use
    quality: 0.95
    for best quality
  6. SVG Vectors: Prefer SVG export for charts and graphics
  1. 性能优化: 优先使用
    scale
    而非
    width
    /
    height
    以获得更好的性能
  2. 字体处理: 设置
    embedFonts: true
    确保自定义字体正确显示
  3. CORS问题: 如果图像加载失败,启用
    useProxy: true
  4. 大型元素: 对于复杂页面,将其拆分为较小的部分进行捕获
  5. 质量设置: 对于PNG/JPG,使用
    quality: 0.95
    以获得最佳质量
  6. SVG矢量图: 对于图表和图形,优先选择SVG导出

Troubleshooting

故障排除

Elements Not Rendering

元素未渲染

  • Check if element has sufficient height/width
  • Verify CSS is fully loaded before capture
  • Try
    straighten: false
    if transforms are causing issues
  • 检查元素是否有足够的高度/宽度
  • 确保捕获前CSS已完全加载
  • 如果变换导致问题,尝试设置
    straighten: false

Missing Fonts

字体缺失

  • Set
    embedFonts: true
  • Ensure fonts are loaded before calling snapdom
  • Check browser console for font loading errors
  • 设置
    embedFonts: true
  • 确保调用snapdom前字体已加载完成
  • 检查浏览器控制台的字体加载错误

CORS Issues

CORS问题

  • Enable
    useProxy: true
  • Use custom proxy URL if default fails
  • Check if resources are from same origin
  • 启用
    useProxy: true
  • 如果默认代理失败,使用自定义代理URL
  • 检查资源是否来自同源

Performance Issues

性能问题

  • Reduce
    scale
    value
  • Use
    noShadows: true
    to skip shadow rendering
  • Consider splitting large captures into smaller sections
  • 降低
    scale
  • 设置
    noShadows: true
    跳过阴影渲染
  • 考虑将大型捕获拆分为较小的部分",