@4keys/dom-to-image 中文文档教程

发布于 6年前 浏览 32 项目主页 更新于 3年前

DOM to Image

Build Status

What is it

dom-to-image 是一个可以将任意 DOM 节点转换为图像的库 用 JavaScript 编写的矢量 (SVG) 或光栅(PNG 或 JPEG)图像。 它是 基于 Paul Bakaus 的 domvas 并且已经完全重写,修复了一些错误和一些新的 添加了功能(如网络字体和图像支持)。

Installation

NPM

npm install dom-to-image

然后加载

/* in ES 6 */
import domtoimage from 'dom-to-image';
/* in ES 5 */
var domtoimage = require('dom-to-image');

Bower

bower install dom-to-image

包括 src/dom-to-image.js 或 < code>dist/dom-to-image.min.js 在你的页面 它将使 domtoimage 变量在全局范围内可用。

<script src="path/to/dom-to-image.min.js" />
<script>
  domtoimage.toPng(node)
  //...
</script>

Usage

所有顶级函数都接受 DOM 节点和渲染选项, 并返回承诺,这些承诺由相应的数据 URL 实现。
获取 PNG 图像 base64 编码数据 URL 并立即显示:

var node = document.getElementById('my-node');

domtoimage.toPng(node)
    .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
    })
    .catch(function (error) {
        console.error('oops, something went wrong!', error);
    });

获取 PNG 图像 blob 并下载它(使用 FileSaver , 例如):

domtoimage.toBlob(document.getElementById('my-node'))
    .then(function (blob) {
        window.saveAs(blob, 'my-node.png');
    });

保存并下载压缩的 JPEG 图像:

domtoimage.toJpeg(document.getElementById('my-node'), { quality: 0.95 })
    .then(function (dataUrl) {
        var link = document.createElement('a');
        link.download = 'my-image-name.jpeg';
        link.href = dataUrl;
        link.click();
    });

获取 SVG 数据 URL,但过滤掉所有 元素:

function filter (node) {
    return (node.tagName !== 'i');
}

domtoimage.toSvg(document.getElementById('my-node'), {filter: filter})
    .then(function (dataUrl) {
        /* do something */
    });

获取原始像素数据作为 Uint8Array 每 4 个数组元素代表一个像素的 RGBA 数据:

var node = document.getElementById('my-node');

domtoimage.toPixelData(node)
    .then(function (pixels) {
        for (var y = 0; y < node.scrollHeight; ++y) {
          for (var x = 0; x < node.scrollWidth; ++x) {
            pixelAtXYOffset = (4 * y * node.scrollHeight) + (4 * x);
            /* pixelAtXY is a Uint8Array[4] containing RGBA values of the pixel at (x, y) in the range 0..255 */
            pixelAtXY = pixels.slice(pixelAtXYOffset, pixelAtXYOffset + 4);
          }
        }
    });

impl 下的所有函数都不是公共 API,仅公开 用于单元测试。


Rendering options

filter

以 DOM 节点作为参数的函数。 如果通过节点应该返回 true 应该包含在输出中(排除节点意味着排除它的 儿童也一样)。 不在根节点上调用。

bgcolor

背景颜色的字符串值,任何有效的 CSS 颜色值。

height, width

渲染前应用于节点的高度和宽度(以像素为单位)。

style

一个对象,其属性在渲染之前被复制到节点的样式。 您可能需要查看此参考资料 用于 CSS 属性的 JavaScript 名称。

quality

一个介于 0 和 1 之间的数字,表示图像质量(例如 0.92 => 92%) JPEG 图片。 默认为 1.0 (100%)

cacheBust

设置为 true 以将当前时间作为查询字符串附加到 URL 请求以启用缓存清除。 默认为 false

imagePlaceholder

获取图像失败时将使用的占位符图像的数据 URL。 默认为 undefined 并且会在失败的图像上抛出错误

Browsers

它在最新的 Chrome 和 Firefox(当时分别为 49 和 45)上进行了测试 写作),Chrome 在大型 DOM 树上的表现要好得多, 可能是因为它对 SVG 的支持更高效,而且它支持 CSSStyleDeclaration.cssText 属性。

Internet Explorer 不受(也不会)支持,因为它不支持 SVG 标签

Safari 不支持,因为它在 > 上使用了更严格的安全模型。 标签。 建议的解决方法是使用 toSvg 并在服务器上呈现。`

Dependencies

Source

目前仅使用标准库,但请确保您的浏览器支持:

Tests

最重要的是,测试取决于:

  • js-imagediff, 比较渲染图像和控制图像

  • ocrad.js,对于 无法比较图像时的部分(由于浏览器 渲染差异)并且只需要测试文本是否被渲染

How it works

可能有一天存在(或者可能已经存在?)一个简单和标准的 将部分 HTML 导出为图像的方法(然后此脚本只能 作为我必须跳过的所有箍的证据才能获得 完成了如此明显的事情),但到目前为止我还没有找到。

这个库使用 SVG 的一个特性,允许有任意的 HTML 内容 在 标签内。 所以,为了渲染那个 DOM 节点 对您来说,采取以下步骤:

  1. 递归克隆原始 DOM 节点

  2. 计算节点和每个子节点的样式并将其复制到 相应的克隆

    • and don't forget to recreate pseudo-elements, as they are not cloned in any way, of course
  3. 嵌入网络字体

    • 找到所有可能代表网络字体的@font-face声明

    • 解析文件URL,下载相应的文件

    • base64-encode和内联内容作为data: URLs

    • concatenate所有处理后的 CSS 规则并将它们放入一个

  4. 嵌入图像

    • 元素中嵌入图像 URL 在 <

    • code>background CSS 属性中使用的内联图像,其方式类似于 fonts

  5. 将克隆出来的节点序列化为XML,将XML

  6. 包装到标签中,再放入SVG中,然后做成一个 数据 URL

  7. 可选地,要将 PNG 内容或原始像素数据作为 Uint8Array,创建一个 以 SVG 为源的图像元素,并将其渲染到屏幕外 画布,你也创建了,然后从画布上读取内容

  8. 完成!

Things to watch out for

  • 如果要呈现的 DOM 节点包含一个 元素 画在上面的东西,应该处理得很好,除非画布是 被污染 - 在这种情况下渲染不会成功。

  • 在撰写本文时,Firefox 存在一些外部样式表问题 (见问题 #13)。 在这种情况下,将捕获并记录错误。

Authors

Anatolii Saienko, Paul Bakaus(原创)

License

麻省理工学院

DOM to Image

Build Status

What is it

dom-to-image is a library which can turn arbitrary DOM node into a vector (SVG) or raster (PNG or JPEG) image, written in JavaScript. It's based on domvas by Paul Bakaus and has been completely rewritten, with some bugs fixed and some new features (like web font and image support) added.

Installation

NPM

npm install dom-to-image

Then load

/* in ES 6 */
import domtoimage from 'dom-to-image';
/* in ES 5 */
var domtoimage = require('dom-to-image');

Bower

bower install dom-to-image

Include either src/dom-to-image.js or dist/dom-to-image.min.js in your page and it will make the domtoimage variable available in the global scope.

<script src="path/to/dom-to-image.min.js" />
<script>
  domtoimage.toPng(node)
  //...
</script>

Usage

All the top level functions accept DOM node and rendering options, and return promises, which are fulfilled with corresponding data URLs.
Get a PNG image base64-encoded data URL and display right away:

var node = document.getElementById('my-node');

domtoimage.toPng(node)
    .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
    })
    .catch(function (error) {
        console.error('oops, something went wrong!', error);
    });

Get a PNG image blob and download it (using FileSaver, for example):

domtoimage.toBlob(document.getElementById('my-node'))
    .then(function (blob) {
        window.saveAs(blob, 'my-node.png');
    });

Save and download a compressed JPEG image:

domtoimage.toJpeg(document.getElementById('my-node'), { quality: 0.95 })
    .then(function (dataUrl) {
        var link = document.createElement('a');
        link.download = 'my-image-name.jpeg';
        link.href = dataUrl;
        link.click();
    });

Get an SVG data URL, but filter out all the <i> elements:

function filter (node) {
    return (node.tagName !== 'i');
}

domtoimage.toSvg(document.getElementById('my-node'), {filter: filter})
    .then(function (dataUrl) {
        /* do something */
    });

Get the raw pixel data as a Uint8Array with every 4 array elements representing the RGBA data of a pixel:

var node = document.getElementById('my-node');

domtoimage.toPixelData(node)
    .then(function (pixels) {
        for (var y = 0; y < node.scrollHeight; ++y) {
          for (var x = 0; x < node.scrollWidth; ++x) {
            pixelAtXYOffset = (4 * y * node.scrollHeight) + (4 * x);
            /* pixelAtXY is a Uint8Array[4] containing RGBA values of the pixel at (x, y) in the range 0..255 */
            pixelAtXY = pixels.slice(pixelAtXYOffset, pixelAtXYOffset + 4);
          }
        }
    });

All the functions under impl are not public API and are exposed only for unit testing.


Rendering options

filter

A 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). Not called on the root node.

bgcolor

A string value for the background color, any valid CSS color value.

height, width

Height and width in pixels to be applied to node before rendering.

style

An object whose properties to be copied to node's style before rendering. You might want to check this reference for JavaScript names of CSS properties.

quality

A number between 0 and 1 indicating image quality (e.g. 0.92 => 92%) of the JPEG image. Defaults to 1.0 (100%)

cacheBust

Set to true to append the current time as a query string to URL requests to enable cache busting. Defaults to false

imagePlaceholder

A data URL for a placeholder image that will be used when fetching an image fails. Defaults to undefined and will throw an error on failed images

Browsers

It's tested on latest Chrome and Firefox (49 and 45 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.

Internet Explorer is not (and will not be) supported, as it does not support SVG <foreignObject> tag

Safari is not supported, as it uses a stricter security model on <foreignObject> tag. Suggested workaround is to use toSvg and render on the server.`

Dependencies

Source

Only standard lib is currently used, but make sure your browser supports:

Tests

Most importantly, tests depend on:

  • js-imagediff, to compare rendered and control images

  • ocrad.js, for the parts when you can't compare images (due to the browser rendering differences) and just have to test whether the text is rendered

How it works

There 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.

This library uses a feature of SVG that allows having arbitrary HTML content inside of the <foreignObject> tag. So, in order to render that DOM node for you, following steps are taken:

  1. Clone the original DOM node recursively

  2. Compute the style for the node and each sub-node and copy it to corresponding clone

    • and don't forget to recreate pseudo-elements, as they are not cloned in any way, of course
  3. Embed web fonts

    • find all the @font-face declarations that might represent web fonts

    • parse file URLs, download corresponding files

    • base64-encode and inline content as data: URLs

    • concatenate all the processed CSS rules and put them into one <style> element, then attach it to the clone

  4. Embed images

    • embed image URLs in <img> elements

    • inline images used in background CSS property, in a fashion similar to fonts

  5. Serialize the cloned node to XML

  6. Wrap XML into the <foreignObject> tag, then into the SVG, then make it a data URL

  7. 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

  8. Done!

Things to watch out for

  • if the DOM node you want to render includes a <canvas> element with something drawn on it, it should be handled fine, unless the canvas is tainted - in this case rendering will rather not succeed.

  • at the time of writing, Firefox has a problem with some external stylesheets (see issue #13). In such case, the error will be caught and logged.

Authors

Anatolii Saienko, Paul Bakaus (original idea)

License

MIT

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文