snapdom
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSnapDOM 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/snapdombash
npm install @zumer/snapdomor
or
yarn add @zumer/snapdom
undefinedyarn add @zumer/snapdom
undefinedCDN (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
关键配置选项参考
| Option | Type | Purpose |
|---|---|---|
| Number | Scale output (e.g., 2 for 2x resolution) |
| Number | Custom output width in pixels |
| Number | Custom output height in pixels |
| Boolean | Include non-icon @font-face rules |
| String|Boolean | Enable CORS proxy (URL or true for default) |
| String | CSS selector for elements to hide |
| Boolean | Remove translate/rotate transforms |
| Boolean | Strip shadow effects |
| 选项 | 类型 | 用途 |
|---|---|---|
| 数字 | 缩放输出(例如,2表示2倍分辨率) |
| 数字 | 自定义输出宽度(像素) |
| 数字 | 自定义输出高度(像素) |
| 布尔值 | 包含非图标@font-face规则 |
| 字符串|布尔值 | 启用CORS代理(URL或true使用默认代理) |
| 字符串 | 要隐藏元素的CSS选择器 |
| 布尔值 | 移除平移/旋转变换 |
| 布尔值 | 去除阴影效果 |
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 → afterExportjavascript
// 使用自定义导出器扩展功能
snapdom.plugins([pluginFactory, { colorOverlay: true }]);
// 钩子到生命周期
defineExports(context) {
return {
pdf: async (ctx, opts) => { /* 生成PDF */ }
};
}
// 可用的生命周期钩子:
// beforeSnap → beforeClone → afterClone →
// beforeRender → beforeExport → afterExportPerformance Comparison
性能对比
SnapDOM significantly outperforms html2canvas:
| Scenario | SnapDOM | html2canvas | Improvement |
|---|---|---|---|
| Small (200×100) | 1.6ms | 68ms | 42x faster |
| Medium (800×600) | 12ms | 280ms | 23x faster |
| Large (4000×2000) | 171ms | 1,800ms | 10x faster |
SnapDOM的性能显著优于html2canvas:
| 场景 | SnapDOM | html2canvas | 提升幅度 |
|---|---|---|---|
| 小型元素(200×100) | 1.6ms | 68ms | 快42倍 |
| 中型元素(800×600) | 12ms | 280ms | 快23倍 |
| 大型元素(4000×2000) | 171ms | 1,800ms | 快10倍 |
Development
开发指南
Setup
环境搭建
bash
git clone https://github.com/zumerlab/snapdom.git
cd snapdom
npm installbash
git clone https://github.com/zumerlab/snapdom.git
cd snapdom
npm installBuild
构建
bash
npm run compilebash
npm run compileTesting
测试
bash
npm testbash
npm testBrowser 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
文档
- Official Website: https://snapdom.dev/
- GitHub Repository: https://github.com/zumerlab/snapdom
- NPM Package: https://www.npmjs.com/package/@zumer/snapdom
- License: MIT
- 官方网站: https://snapdom.dev/
- GitHub仓库: https://github.com/zumerlab/snapdom
- NPM包: https://www.npmjs.com/package/@zumer/snapdom
- 许可证: MIT
scripts/
scripts/
Add helper scripts here for automation, e.g.:
- - Capture multiple elements
batch-screenshot.js - - Convert snapshots to PDF
pdf-export.js - - Compare SVG vs PNG quality
compare-outputs.js
在此处添加自动化辅助脚本,例如:
- - 捕获多个元素
batch-screenshot.js - - 将快照转换为PDF
pdf-export.js - - 对比SVG与PNG的质量
compare-outputs.js
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
相关工具
- html2canvas - Alternative DOM capture (slower but more compatible)
- Orbit CSS Toolkit - Companion toolkit by Zumerlab (https://github.com/zumerlab/orbit)
- html2canvas - 另一种DOM捕获工具(速度较慢但兼容性更好)
- Orbit CSS Toolkit - Zumerlab出品的配套工具包(https://github.com/zumerlab/orbit)
Tips & Best Practices
技巧与最佳实践
- Performance: Use instead of
scale/widthfor better performanceheight - Fonts: Set to ensure custom fonts appear correctly
embedFonts: true - CORS Issues: Use if images fail to load
useProxy: true - Large Elements: Break into smaller chunks for complex pages
- Quality: For PNG/JPG, use for best quality
quality: 0.95 - SVG Vectors: Prefer SVG export for charts and graphics
- 性能优化: 优先使用而非
scale/width以获得更好的性能height - 字体处理: 设置确保自定义字体正确显示
embedFonts: true - CORS问题: 如果图像加载失败,启用
useProxy: true - 大型元素: 对于复杂页面,将其拆分为较小的部分进行捕获
- 质量设置: 对于PNG/JPG,使用以获得最佳质量
quality: 0.95 - SVG矢量图: 对于图表和图形,优先选择SVG导出
Troubleshooting
故障排除
Elements Not Rendering
元素未渲染
- Check if element has sufficient height/width
- Verify CSS is fully loaded before capture
- Try if transforms are causing issues
straighten: false
- 检查元素是否有足够的高度/宽度
- 确保捕获前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 value
scale - Use to skip shadow rendering
noShadows: true - Consider splitting large captures into smaller sections
- 降低值
scale - 设置跳过阴影渲染
noShadows: true - 考虑将大型捕获拆分为较小的部分",