{"id":19737384,"url":"https://github.com/mkhuda/dom-screenshot","last_synced_at":"2026-05-06T06:39:17.783Z","repository":{"id":57793335,"uuid":"527870778","full_name":"mkhuda/dom-screenshot","owner":"mkhuda","description":"DOM screenshot by dom-to-image","archived":false,"fork":false,"pushed_at":"2022-08-26T08:09:22.000Z","size":35,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-23T07:06:32.241Z","etag":null,"topics":["dom","javascript","react","screencapture","screenshot","typescript-definitions","vuejs"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mkhuda.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-08-23T06:59:42.000Z","updated_at":"2022-08-25T07:15:44.000Z","dependencies_parsed_at":"2022-08-26T02:11:02.691Z","dependency_job_id":null,"html_url":"https://github.com/mkhuda/dom-screenshot","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mkhuda%2Fdom-screenshot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mkhuda%2Fdom-screenshot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mkhuda%2Fdom-screenshot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mkhuda%2Fdom-screenshot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mkhuda","download_url":"https://codeload.github.com/mkhuda/dom-screenshot/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241062927,"owners_count":19902994,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dom","javascript","react","screencapture","screenshot","typescript-definitions","vuejs"],"created_at":"2024-11-12T01:10:49.847Z","updated_at":"2026-05-06T06:39:17.774Z","avatar_url":"https://github.com/mkhuda.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# dom-screenshot\n\n[![Build Status](https://app.travis-ci.com/mkhuda/dom-screenshot.svg?branch=main)](https://app.travis-ci.com/mkhuda/dom-screenshot) [![npm version](https://badge.fury.io/js/%40mkhuda%2Fdom-screenshot.svg)](https://badge.fury.io/js/%40mkhuda%2Fdom-screenshot)\n\nA modern TypeScript library to capture DOM elements as **SVG**, **PNG**, **JPEG**, or **Blob** images. Built with latest tooling and fully type-safe.\n\n\u003e Forked \u0026 modified from [dom-to-image](https://github.com/tsayen/dom-to-image)\n\n---\n\n## ✨ Features\n\n- 📸 **Multiple Formats**: SVG (vector), PNG (raster), JPEG (compressed), Blob, Pixel Data\n- 🎨 **Style Preservation**: Captures all CSS styles, colors, gradients, shadows, transforms\n- 📦 **Modern Build**: Rollup with TypeScript, ESM and CommonJS outputs\n- 🔒 **Type Safe**: Full TypeScript support with complete type definitions\n- ⚡ **Fast**: Optimized for performance, lazy initialization of dependencies\n- 🚀 **Production Ready**: Tested and used in real-world applications\n- 🎯 **React Friendly**: Works seamlessly with React via refs\n\n---\n\n## 📚 Documentation\n\n### Quick Reference\n- **🎬 Live Demo** → **[Try it now!](https://dom-screenshot-react.vercel.app/)** (no setup needed)\n- **Getting Started** → See below or check [`EXAMPLES_QUICKSTART.md`](./EXAMPLES_QUICKSTART.md)\n- **React Example** → Run the interactive example in `examples/react-app/`\n- **Testing** → See [`TESTING.md`](./TESTING.md) for test setup\n- **Examples** → Check [`examples/README.md`](./examples/README.md) for detailed examples\n\n### File Guides\n\n| File | Purpose |\n|------|---------|\n| `EXAMPLES_QUICKSTART.md` | Quick start guide for running examples |\n| `TESTING.md` | Testing framework setup and usage |\n| `TESTING_STATUS.md` | Current test status and results |\n| `TEST_SETUP_SUMMARY.md` | Comprehensive testing documentation |\n| `examples/README.md` | Examples overview |\n| `examples/react-app/README.md` | Detailed React example guide |\n| `tests/README.md` | Test infrastructure details |\n\n---\n\n## 🎬 Live Demo\n\n**Try it now!** → **[dom-screenshot React Demo](https://dom-screenshot-react.vercel.app/)**\n\nExperience the library in action with an interactive React application. Capture UI elements as SVG, PNG, or JPEG with live preview! 🚀\n\n---\n\n## 🚀 Quick Start\n\n### Installation\n\n```bash\nnpm install @mkhuda/dom-screenshot\n# or\nyarn add @mkhuda/dom-screenshot\n```\n\n### Basic Usage\n\n```typescript\nimport { domtoimage } from '@mkhuda/dom-screenshot';\n\n// Get the element to capture\nconst element = document.getElementById('content');\n\n// Capture as SVG\nconst svg = await domtoimage.toSvg(element);\n\n// Capture as PNG\nconst png = await domtoimage.toPng(element);\n\n// Capture as JPEG\nconst jpeg = await domtoimage.toJpeg(element);\n\n// Get as Blob\nconst blob = await domtoimage.toBlob(element);\n\n// Get pixel data\nconst pixelData = await domtoimage.toPixelData(element);\n```\n\n### React Example\n\n```typescript\nimport { useRef } from 'react';\nimport { domtoimage } from '@mkhuda/dom-screenshot';\n\nexport function MyComponent() {\n  const contentRef = useRef\u003cHTMLDivElement\u003e(null);\n\n  const handleCapture = async () =\u003e {\n    if (!contentRef.current) return;\n\n    try {\n      const png = await domtoimage.toPng(contentRef.current);\n\n      // Download\n      const link = document.createElement('a');\n      link.href = png;\n      link.download = 'screenshot.png';\n      link.click();\n    } catch (error) {\n      console.error('Capture failed:', error);\n    }\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cdiv ref={contentRef}\u003e\n        \u003ch1\u003eContent to capture\u003c/h1\u003e\n        \u003cp\u003eThis will be captured\u003c/p\u003e\n      \u003c/div\u003e\n      \u003cbutton onClick={handleCapture}\u003e📸 Download as PNG\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n---\n\n## 📸 API Reference\n\n### Functions\n\n#### `toSvg(node, options?)`\nRenders DOM node to SVG data URL (scalable vector format).\n\n**Returns:** `Promise\u003cstring\u003e` - SVG data URL\n\n**Best for:** UI components, diagrams, simple graphics\n\n```typescript\nconst svg = await domtoimage.toSvg(element);\n```\n\n#### `toPng(node, options?)`\nRenders DOM node to PNG data URL (lossless raster format).\n\n**Returns:** `Promise\u003cstring\u003e` - PNG data URL\n\n**Best for:** Screenshots, general purpose captures\n\n```typescript\nconst png = await domtoimage.toPng(element);\n```\n\n#### `toJpeg(node, options?)`\nRenders DOM node to JPEG data URL (lossy compressed format).\n\n**Returns:** `Promise\u003cstring\u003e` - JPEG data URL\n\n**Best for:** Photos, space-constrained scenarios\n\n```typescript\nconst jpeg = await domtoimage.toJpeg(element, { quality: 0.95 });\n```\n\n#### `toBlob(node, options?)`\nRenders DOM node to Blob object.\n\n**Returns:** `Promise\u003cBlob\u003e` - Blob object\n\n**Best for:** Uploading to server, efficient data handling\n\n```typescript\nconst blob = await domtoimage.toBlob(element);\n```\n\n#### `toPixelData(node, options?)`\nExtracts raw pixel data from DOM node.\n\n**Returns:** `Promise\u003cUint8ClampedArray\u003e` - RGBA pixel data\n\n**Best for:** Image processing, pixel manipulation\n\n```typescript\nconst pixelData = await domtoimage.toPixelData(element);\n```\n\n### Options\n\n```typescript\ninterface DomScreenshotOptions {\n  width?: number;           // Override width\n  height?: number;          // Override height\n  bgcolor?: string;         // Background color\n  quality?: number;         // JPEG quality (0-1)\n  style?: CSSStyleDeclaration;  // Additional styles\n  filter?: (node: Node) =\u003e boolean;  // Filter nodes\n  cacheBust?: boolean;      // Bust cache with random query\n  imagePlaceholder?: string; // Placeholder for broken images\n}\n```\n\n---\n\n## 🎯 Real-World Use Cases\n\n### 1. Export Feature\nLet users download rendered UI as images:\n```typescript\nconst png = await domtoimage.toPng(contentElement);\ndownloadFile(png, 'export.png');\n```\n\n### 2. Report Generation\nCreate visual reports from data:\n```typescript\nconst reports = await Promise.all([\n  domtoimage.toPng(chart1),\n  domtoimage.toPng(chart2),\n  domtoimage.toPng(table),\n]);\n```\n\n### 3. Screenshot Tools\nBuild screenshot applications:\n```typescript\nconst screenshots = [];\nscreenshots.push(await domtoimage.toPng(screen1));\nscreenshots.push(await domtoimage.toPng(screen2));\n```\n\n### 4. Documentation\nAuto-capture UI for documentation:\n```typescript\nconst componentScreenshot = await domtoimage.toSvg(component);\n```\n\n---\n\n## 🧪 Testing\n\nThe project includes a comprehensive test suite with:\n\n- ✅ 20 infrastructure tests\n- ✅ Unit tests for all functions\n- ✅ Integration tests\n- ✅ Custom test matchers\n- ✅ Full TypeScript support\n\n### Run Tests\n\n```bash\n# Run tests once\nnpm run test:run\n\n# Watch mode\nnpm run test:watch\n\n# UI dashboard\nnpm run test:ui\n\n# Coverage report\nnpm run test:coverage\n```\n\nSee [`TESTING.md`](./TESTING.md) for detailed testing information.\n\n---\n\n## 💻 Examples\n\n### 🎬 Live Demo\n\nExperience the library instantly without any setup:\n- **[dom-screenshot React Demo](https://dom-screenshot-react.vercel.app/)** - Interactive demo with live preview\n- Supports SVG, PNG, JPEG capture\n- Real-time gallery view\n- Auto-download functionality\n\n### React Example App\n\nA complete, production-ready React application demonstrating all features:\n\n**Features:**\n- Capture as SVG, PNG, JPEG\n- Live preview gallery\n- Auto-download files\n- Beautiful responsive UI\n- Full TypeScript\n\n**Quick Start:**\n```bash\nnpm run example:dev\n```\n\nOpens at `http://localhost:5173`\n\nFor detailed information, see:\n- [`EXAMPLES_QUICKSTART.md`](./EXAMPLES_QUICKSTART.md) - Quick reference\n- [`examples/README.md`](./examples/README.md) - Examples overview\n- [`examples/react-app/README.md`](./examples/react-app/README.md) - Detailed guide\n\n---\n\n## 🏗️ Project Structure\n\n```\ndom-screenshot/\n├── src/\n│   ├── dom-screenshot.ts         # Main library\n│   └── types/\n│       └── options.ts             # Type definitions\n├── dist/\n│   ├── dom-screenshot.esm.js      # ES Module\n│   ├── dom-screenshot.min.js      # IIFE (minified)\n│   └── dom-screenshot.d.ts        # TypeScript types\n├── tests/\n│   ├── setup.ts                   # Test configuration\n│   ├── helpers/                   # Test utilities\n│   ├── mocks/                     # Mock implementations\n│   ├── fixtures/                  # Test data\n│   └── unit/\n│       ├── simple.test.ts         # Infrastructure tests\n│       └── basic.test.ts          # Feature tests\n├── examples/\n│   └── react-app/                 # React example application\n├── vitest.config.mts              # Test runner config\n├── tsconfig.json                  # TypeScript config\n├── rollup.config.mjs              # Build config\n└── package.json\n```\n\n---\n\n## 🛠️ Development\n\n### Prerequisites\n- Node.js 22.12.0 (pinned with Volta)\n- npm or yarn\n\n### Setup\n\n```bash\n# Install dependencies\nnpm install\n\n# Build library\nnpm run build\n\n# Watch for changes\nnpm run watch\n```\n\n### Build Commands\n\n```bash\nnpm run build              # Build production\nnpm run test:run           # Run tests\nnpm run test:watch         # Watch tests\nnpm run test:ui            # Test UI dashboard\nnpm run example:dev        # Run React example\nnpm run example:build      # Build React example\n```\n\n---\n\n## 📊 What's New (TypeScript Migration)\n\n### ✅ Completed\n\n- ✅ Full TypeScript migration\n- ✅ Strict type checking enabled\n- ✅ Modern build tooling (Rollup 4.x, TypeScript 5.x)\n- ✅ ESM and CommonJS dual output\n- ✅ Complete test suite (20+ tests passing)\n- ✅ Production-ready React example\n- ✅ Comprehensive documentation\n\n### 🎯 Quality Metrics\n\n| Metric | Status |\n|--------|--------|\n| TypeScript | ✅ Full coverage with strict mode |\n| Tests | ✅ 20+ tests passing |\n| Build | ✅ 0 errors |\n| Output | ✅ ESM + IIFE dual format |\n| Types | ✅ Complete definitions |\n| Docs | ✅ Comprehensive guides |\n\n---\n\n## 🚀 Browser Support\n\n- ✅ Chrome/Chromium (latest)\n- ✅ Firefox (latest)\n- ✅ Safari (latest)\n- ✅ Edge (latest)\n\nFor older browsers, ensure required polyfills are present.\n\n---\n\n## 🔄 Format Comparison\n\n| Format | Use Case | Size | Speed | Quality |\n|--------|----------|------|-------|---------|\n| **SVG** | UI/Diagrams | Smallest | Fastest | Vector |\n| **PNG** | General Purpose | Medium | Medium | Lossless |\n| **JPEG** | Photos | Smallest | Slower | Lossy |\n| **Blob** | Server Upload | Any | Any | Any |\n\n---\n\n## ⚙️ Advanced Options\n\n### Custom Dimensions\n\n```typescript\nconst png = await domtoimage.toPng(element, {\n  width: 1920,\n  height: 1080,\n});\n```\n\n### Background Color\n\n```typescript\nconst png = await domtoimage.toPng(element, {\n  bgcolor: '#ffffff',\n});\n```\n\n### JPEG Quality\n\n```typescript\nconst jpeg = await domtoimage.toJpeg(element, {\n  quality: 0.95,  // 0 to 1\n});\n```\n\n### Filter Nodes\n\n```typescript\nconst svg = await domtoimage.toSvg(element, {\n  filter: (node) =\u003e {\n    // Exclude elements with class 'no-capture'\n    if (node instanceof HTMLElement) {\n      return !node.classList.contains('no-capture');\n    }\n    return true;\n  },\n});\n```\n\n### Cache Busting\n\n```typescript\nconst png = await domtoimage.toPng(element, {\n  cacheBust: true,  // Add random query string to URLs\n});\n```\n\n---\n\n## 🐛 Troubleshooting\n\n### Styles Not Captured\n- Ensure styles are inline or in `\u003cstyle\u003e` tags\n- External stylesheets may not be included\n- Use computed styles for debugging\n\n### Canvas-Related Errors\n- SVG capture works in all environments\n- PNG/JPEG may need browser environment\n- Always use try-catch blocks\n\n### Performance Issues\n- Use SVG for simple UI elements\n- Break large captures into sections\n- Cache element references\n\n### Import Errors\n- Ensure library is built: `npm run build`\n- Check Node.js version: `node --version`\n- Try reinstalling: `rm -rf node_modules \u0026\u0026 npm install`\n\n---\n\n## 📄 File Guides\n\n### Main Documentation Files\n\n#### `TESTING.md`\nQuick reference for:\n- Running tests\n- Test commands\n- Test patterns\n\n#### `TESTING_STATUS.md`\nCurrent test status:\n- Test results\n- Coverage information\n- Known issues\n\n#### `TEST_SETUP_SUMMARY.md`\nComprehensive testing:\n- Setup details\n- Infrastructure overview\n- Test organization\n\n#### `EXAMPLES_QUICKSTART.md`\nQuick start for examples:\n- Installation steps\n- Running instructions\n- Troubleshooting\n\n#### `examples/README.md`\nExamples overview:\n- Available examples\n- Features demonstrated\n- Technologies used\n\n#### `examples/react-app/README.md`\nReact example details:\n- Project structure\n- Component documentation\n- Customization guide\n\n#### `tests/README.md`\nTesting infrastructure:\n- Test setup\n- Helper utilities\n- Mock implementations\n\n---\n\n## 🤝 Contributing\n\nContributions are welcome! Please:\n\n1. Fork the repository\n2. Create a feature branch\n3. Add tests for new features\n4. Ensure all tests pass\n5. Submit a pull request\n\nSee `TESTING.md` for test setup instructions.\n\n---\n\n## 📝 License\n\n[MIT](https://choosealicense.com/licenses/mit/)\n\n---\n\n## 🙏 Acknowledgments\n\n- Original library: [dom-to-image](https://github.com/tsayen/dom-to-image) by tsayen\n- Modern tooling and TypeScript migration by Muhammad K. Huda\n\n---\n\n## 📞 Support\n\n- 📖 Check the documentation files listed above\n- 🐛 Found a bug? [Open an issue](https://github.com/mkhuda/dom-screenshot/issues)\n- 💬 Have questions? Check existing issues or discussions\n- 🚀 Want to contribute? See Contributing section\n\n---\n\n**Ready to capture?**\n- 🎬 Try the **[Live Demo](https://dom-screenshot-react.vercel.app/)** instantly\n- 📖 Read the **[Quick Start](#-quick-start)**\n- 💻 Check the **[React Example](#-examples)**\n\nLet's start capturing! 📸\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmkhuda%2Fdom-screenshot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmkhuda%2Fdom-screenshot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmkhuda%2Fdom-screenshot/lists"}