{"id":13406509,"url":"https://github.com/bubkoo/html-to-image","last_synced_at":"2025-05-13T15:02:39.230Z","repository":{"id":37336749,"uuid":"113022549","full_name":"bubkoo/html-to-image","owner":"bubkoo","description":"✂️ Generates an image from a DOM node using HTML5 canvas and SVG.","archived":false,"fork":false,"pushed_at":"2025-02-14T01:43:44.000Z","size":92080,"stargazers_count":6255,"open_issues_count":152,"forks_count":590,"subscribers_count":30,"default_branch":"master","last_synced_at":"2025-04-17T22:02:54.865Z","etag":null,"topics":["canvas","dataurl","dom","image","javascript","picture","screenshot","svg"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/bubkoo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-12-04T09:29:15.000Z","updated_at":"2025-04-17T03:27:24.000Z","dependencies_parsed_at":"2023-12-13T02:39:52.056Z","dependency_job_id":"b31b1e9c-19dd-4b67-8b30-6a1ad2fa85b1","html_url":"https://github.com/bubkoo/html-to-image","commit_stats":{"total_commits":382,"total_committers":50,"mean_commits":7.64,"dds":0.5366492146596858,"last_synced_commit":"b751cbf212ccc7909077bc105b0630f9c845389a"},"previous_names":[],"tags_count":66,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bubkoo%2Fhtml-to-image","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bubkoo%2Fhtml-to-image/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bubkoo%2Fhtml-to-image/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bubkoo%2Fhtml-to-image/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bubkoo","download_url":"https://codeload.github.com/bubkoo/html-to-image/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250343925,"owners_count":21415037,"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":["canvas","dataurl","dom","image","javascript","picture","screenshot","svg"],"created_at":"2024-07-30T19:02:32.172Z","updated_at":"2025-04-23T00:02:00.535Z","avatar_url":"https://github.com/bubkoo.png","language":"TypeScript","funding_links":[],"categories":["Libraries","TypeScript","Uncategorized","🎨 Design \u0026 Creative","语言资源库","前端开发框架及项目","canvas","About The Project"],"sub_categories":["Poster and Screenshot","Uncategorized","typescript","其他_文本生成、文本对话","Built With"],"readme":"\u003ch1 align=\"center\"\u003ehtml-to-image\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\u003cstrong\u003e✂️ Generates an image from a DOM node using HTML5 canvas and SVG.\u003c/strong\u003e\u003c/p\u003e\n\n\u003cp align=\"center\"\u003eFork from \u003ca href=\"https://github.com/tsayen/dom-to-image\" rel=\"nofollow\"\u003edom-to-image\u003c/a\u003e with more maintainable code and some new features.\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://github.com/bubkoo/html-to-image/actions/workflows/ci.yml\"\u003e\u003cimg alt=\"build\" src=\"https://img.shields.io/github/actions/workflow/status/bubkoo/html-to-image/ci.yml?branch=master\u0026logo=github\u0026style=for-the-badge\"\u003e\u003c/a\u003e\n\u003ca href=\"https://app.codecov.io/gh/bubkoo/html-to-image\"\u003e\u003cimg alt=\"coverage\" src=\"https://img.shields.io/codecov/c/gh/bubkoo/html-to-image?logo=codecov\u0026style=for-the-badge\u0026token=BWweeU2uNX\"\u003e\u003c/a\u003e\n\u003ca href=\"https://www.npmjs.com/package/html-to-image\" rel=\"nofollow\"\u003e\u003cimg alt=\"NPM Package\" src=\"https://img.shields.io/npm/v/html-to-image.svg?logo=npm\u0026style=for-the-badge\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://www.npmjs.com/package/html-to-image\" rel=\"nofollow\"\u003e\u003cimg alt=\"NPM Downloads\" src=\"http://img.shields.io/npm/dm/html-to-image.svg?logo=npm\u0026style=for-the-badge\" /\u003e\u003c/a\u003e\n\n\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"/LICENSE\"\u003e\u003cimg src=\"https://img.shields.io/github/license/bubkoo/html-to-image?style=for-the-badge\" alt=\"MIT License\"\u003e\u003c/a\u003e\n\u003ca href=\"https://www.typescriptlang.org\"\u003e\u003cimg alt=\"Language\" src=\"https://img.shields.io/badge/language-TypeScript-blue.svg?style=for-the-badge\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/bubkoo/html-to-image/pulls\"\u003e\u003cimg alt=\"PRs Welcome\" src=\"https://img.shields.io/badge/PRs-Welcome-brightgreen.svg?style=for-the-badge\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n## Install\n\n```shell\nnpm install --save html-to-image\n```\n\n## Usage\n\n```js\n/* ES6 */\nimport * as htmlToImage from 'html-to-image';\nimport { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image';\n\n/* ES5 */\nvar htmlToImage = require('html-to-image');\n```\n\nAll the top level functions accept DOM node and rendering options, and return a promise fulfilled with corresponding dataURL:\n\n- [toPng](#toPng)\n- [toSvg](#toSvg)\n- [toJpeg](#toJpeg)\n- [toBlob](#toBlob)\n- [toCanvas](#toCanvas)\n- [toPixelData](#toPixelData)\n\nGo with the following examples.\n\n#### toPng\nGet a PNG image base64-encoded data URL and display it right away:\n\n```js\nconst node = document.getElementById('my-node');\n\nhtmlToImage\n  .toPng(node)\n  .then((dataUrl) =\u003e {\n    const img = new Image();\n    img.src = dataUrl;\n    document.body.appendChild(img);\n  })\n  .catch((err) =\u003e {\n    console.error('oops, something went wrong!', err);\n  });\n```\n\nGet a PNG image base64-encoded data URL and download it (using [download](https://github.com/rndme/download)):\n\n```js\nhtmlToImage\n  .toPng(document.getElementById('my-node'))\n  .then((dataUrl) =\u003e download(dataUrl, 'my-node.png'));\n```\n\n#### toSvg\nGet an SVG data URL, but filter out all the `\u003ci\u003e` elements:\n\n```js\nfunction filter (node) {\n  return (node.tagName !== 'i');\n}\n\nhtmlToImage\n  .toSvg(document.getElementById('my-node'), { filter: filter })\n  .then(function (dataUrl) {\n    /* do something */\n  });\n```\n\n#### toJpeg\nSave and download a compressed JPEG image:\n\n```js\nhtmlToImage\n  .toJpeg(document.getElementById('my-node'), { quality: 0.95 })\n  .then(function (dataUrl) {\n    var link = document.createElement('a');\n    link.download = 'my-image-name.jpeg';\n    link.href = dataUrl;\n    link.click();\n  });\n```\n\n#### toBlob\nGet a PNG image blob and download it (using [FileSaver](https://github.com/eligrey/FileSaver.js)):\n\n```js\nhtmlToImage\n  .toBlob(document.getElementById('my-node'))\n  .then(function (blob) {\n    if (window.saveAs) {\n      window.saveAs(blob, 'my-node.png');\n    } else {\n     FileSaver.saveAs(blob, 'my-node.png');\n   }\n  });\n```\n\n#### toCanvas\nGet a HTMLCanvasElement, and display it right away:\n\n```js\nhtmlToImage\n  .toCanvas(document.getElementById('my-node'))\n  .then(function (canvas) {\n    document.body.appendChild(canvas);\n  });\n```\n\n#### toPixelData\nGet the raw pixel data as a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) with every 4 array elements representing the RGBA data of a pixel:\n\n```js\nvar node = document.getElementById('my-node');\n\nhtmlToImage\n  .toPixelData(node)\n  .then(function (pixels) {\n    for (var y = 0; y \u003c node.scrollHeight; ++y) {\n      for (var x = 0; x \u003c node.scrollWidth; ++x) {\n        pixelAtXYOffset = (4 * y * node.scrollHeight) + (4 * x);\n        /* pixelAtXY is a Uint8Array[4] containing RGBA values of the pixel at (x, y) in the range 0..255 */\n        pixelAtXY = pixels.slice(pixelAtXYOffset, pixelAtXYOffset + 4);\n      }\n    }\n  });\n```\n\n#### React\n```tsx\nimport React, { useCallback, useRef } from 'react';\nimport { toPng } from 'html-to-image';\n\nconst App: React.FC = () =\u003e {\n  const ref = useRef\u003cHTMLDivElement\u003e(null)\n\n  const onButtonClick = useCallback(() =\u003e {\n    if (ref.current === null) {\n      return\n    }\n\n    toPng(ref.current, { cacheBust: true, })\n      .then((dataUrl) =\u003e {\n        const link = document.createElement('a')\n        link.download = 'my-image-name.png'\n        link.href = dataUrl\n        link.click()\n      })\n      .catch((err) =\u003e {\n        console.log(err)\n      })\n  }, [ref])\n\n  return (\n    \u003c\u003e\n      \u003cdiv ref={ref}\u003e\n      {/* DOM nodes you want to convert to PNG */}\n      \u003c/div\u003e\n      \u003cbutton onClick={onButtonClick}\u003eClick me\u003c/button\u003e\n    \u003c/\u003e\n  )\n}\n```\n\n## Options\n\n### filter\n\n```ts\n(domNode: HTMLElement) =\u003e boolean\n```\n\nA function taking DOM node as argument. Should return true if passed node should be included in the output. Excluding node means excluding it's children as well.\n\nYou can add filter to every image function. For example, \n\n```ts\nconst filter = (node: HTMLElement) =\u003e {\n  const exclusionClasses = ['remove-me', 'secret-div'];\n  return !exclusionClasses.some((classname) =\u003e node.classList?.contains(classname));\n}\n\nhtmlToImage.toJpeg(node, { quality: 0.95, filter: filter});\n```\nor\n\n```js\nhtmlToImage.toPng(node, {filter:filter})\n```\n\nNot called on the root node.\n\n### backgroundColor\n\nA string value for the background color, any valid CSS color value.\n\n### width, height\n\nWidth and height in pixels to be applied to node before rendering.\n\n### canvasWidth, canvasHeight\n\nAllows to scale the canva's size including the elements inside to a given width and height (in pixels).\n\n### style\n\nAn object whose properties to be copied to node's style before rendering. You might want to check [this reference](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference) for JavaScript names of CSS properties.\n\n### quality\n\nA number between `0` and `1` indicating image quality (e.g. `0.92` =\u003e `92%`) of the JPEG image.\n\nDefaults to `1.0` (`100%`)\n\n### cacheBust\n\nSet to true to append the current time as a query string to URL requests to enable cache busting.\n\nDefaults to `false`\n\n### includeQueryParams\n\nSet false to use all URL as cache key.\nIf the value has falsy value, it will exclude query params from the provided URL.\n\nDefaults to `false`\n\n### imagePlaceholder\n\nA data URL for a placeholder image that will be used when fetching an image fails.\n\nDefaults to an empty string and will render empty areas for failed images.\n\n### pixelRatio\n\nThe pixel ratio of the captured image. Default use the actual pixel ratio of the device. Set `1` to\nuse as initial-scale `1` for the image.\n\n### preferredFontFormat\n\nThe format required for font embedding. This is a useful optimisation when a webfont provider\nspecifies several different formats for fonts in the CSS, for example:\n\n```css\n@font-face {\n  name: 'proxima-nova';\n  src: url(\"...\") format(\"woff2\"), url(\"...\") format(\"woff\"), url(\"...\") format(\"opentype\");\n}\n```\n\nInstead of embedding each format, all formats other than the one specified will be discarded. If\nthis option is not specified then all formats will be downloaded and embedded.\n\n### fontEmbedCSS\n\nWhen supplied, the library will skip the process of parsing and embedding webfont URLs in CSS,\ninstead using this value. This is useful when combined with `getFontEmbedCSS()` to only perform the\nembedding process a single time across multiple calls to library functions.\n\n```javascript\nconst fontEmbedCSS = await htmlToImage.getFontEmbedCSS(element1);\nhtml2Image.toSVG(element1, { fontEmbedCSS });\nhtml2Image.toSVG(element2, { fontEmbedCSS });\n```\n\n### skipAutoScale\n\nWhen supplied, the library will skip the process of scaling extra large doms into the canvas object.\nYou may experience loss of parts of the image if set to `true` and you are exporting a very large image.\n\nDefaults to `false`  \n\n### type\n\nA string indicating the image format. The default type is image/png; that type is also used if the given type isn't supported.\nWhen supplied, the toCanvas function will return a blob matching the given image type and quality. \n\nDefaults to `image/png`\n\n### includeStyleProperties\n\nAn array of style property names. Can be used to manually specify which style properties are included when cloning nodes. This can be useful for performance-critical scenarios.\n\n## Browsers\n\nOnly standard lib is currently used, but make sure your browser supports:\n\n- [Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n- SVG `\u003cforeignObject\u003e` tag\n\nIt's tested on latest Chrome, Firefox and Safari (49, 45 and 16 respectively at the time of writing), with Chrome performing significantly better on big DOM trees, possibly due to it's more performant SVG support, and the fact that it supports `CSSStyleDeclaration.cssText` property.\n\n*Internet Explorer is not (and will not be) supported, as it does not support SVG `\u003cforeignObject\u003e` tag.*\n\n## How it works\n\nThere might some day exist (or maybe already exists?) a simple and standard way of exporting parts of the HTML to image (and then this script can only serve as an evidence of all the hoops I had to jump through in order to get such obvious thing done) but I haven't found one so far.\n\nThis library uses a feature of SVG that allows having arbitrary HTML content inside of the `\u003cforeignObject\u003e` tag. So, in order to render that DOM node for you, following steps are taken:\n\n1. Clone the original DOM node recursively\n2. Compute the style for the node and each sub-node and copy it to corresponding clone \n   - and don't forget to recreate pseudo-elements, as they are not cloned in any way, of course\n3. Embed web fonts\n   - find all the `@font-face` declarations that might represent web fonts\n   - parse file URLs, download corresponding files\n   - base64-encode and inline content as dataURLs\n   - concatenate all the processed CSS rules and put them into one `\u003cstyle\u003e` element, then attach it to the clone\n4. Embed images\n   - embed image URLs in `\u003cimg\u003e` elements\n   - inline images used in `background` CSS property, in a fashion similar to fonts\n5. Serialize the cloned node to XML\n6. Wrap XML into the `\u003cforeignObject\u003e` tag, then into the SVG, then make it a data URL\n7. Optionally, to get PNG content or raw pixel data as a Uint8Array, create an Image element with the SVG as a source, and render it on an off-screen canvas, that you have also created, then read the content from the canvas\n8. Done!\n\n\n## Things to watch out for\n\n- If the DOM node you want to render includes a `\u003ccanvas\u003e` element with something drawn on it, it should be handled fine, unless the canvas is [tainted](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image) - in this case rendering will rather not succeed.\n- Rendering will failed on huge DOM due to the dataURI [limit varies](https://stackoverflow.com/questions/695151/data-protocol-url-size-limitations/41755526#41755526).\n\n## Contributing\n\nPlease let us know how can we help. Do check out [issues](https://github.com/bubkoo/html-to-image/issues) for bug reports or suggestions first.\n\nTo become a contributor, please follow our [contributing guide](/CONTRIBUTING.md).\n\n\u003ca href=\"https://github.com/bubkoo/html-to-image/graphs/contributors\"\u003e\n  \u003cimg src=\"/CONTRIBUTORS.svg\" alt=\"Contributors\" width=\"740\" /\u003e\n\u003c/a\u003e\n\n\n## License\n\nThe scripts and documentation in this project are released under the [MIT License](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbubkoo%2Fhtml-to-image","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbubkoo%2Fhtml-to-image","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbubkoo%2Fhtml-to-image/lists"}