dom-to-image

授权协议 View license
开发语言 JavaScript
所属分类 应用工具、 图形和图像工具
软件类型 开源软件
地区 不详
投 递 者 慎弘化
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

DOM to Image

What is it

dom-to-image is a library which can turn arbitrary DOM node intoa vector (SVG) or raster (PNG or JPEG) image, written in JavaScript. It'sbased on domvas by Paul Bakausand has been completely rewritten, with some bugs fixed and some newfeatures (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 pageand 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 Uint8Arraywith 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 onlyfor unit testing.


Rendering options

filter

A function taking DOM node as argument. Should return true if passed nodeshould be included in the output (excluding node means excluding it'schildren 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 referencefor JavaScript names of CSS properties.

quality

A number between 0 and 1 indicating image quality (e.g. 0.92 => 92%) of theJPEG 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 timeof writing), with Chrome performing significantly better on big DOM trees,possibly due to it's more performant SVG support, and the fact that it supportsCSSStyleDeclaration.cssText property.

Internet Explorer is not (and will not be) supported, as it does not supportSVG <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 theparts when you can't compare images (due to the browserrendering 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 standardway of exporting parts of the HTML to image (and then this script can onlyserve as an evidence of all the hoops I had to jump through in order to getsuch obvious thing done) but I haven't found one so far.

This library uses a feature of SVG that allows having arbitrary HTML contentinside of the <foreignObject> tag. So, in order to render that DOM nodefor 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 tocorresponding clone

    • and don't forget to recreate pseudo-elements, as they are notcloned 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 tofonts

  5. Serialize the cloned node to XML

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

  7. Optionally, to get PNG content or raw pixel data as a Uint8Array, create anImage element with the SVG as a source, and render it on an off-screencanvas, 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 withsomething drawn on it, it should be handled fine, unless the canvas istainted -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

  • Notion – The all-in-one workspace for your notes, tasks, wikis, and databases. 使用svg的一个特性,允许在<foreignobject>标签中包含任意的html内容。 主要是 [XMLSerializer |dom转为svg] dom 转换为 XHTML XMLSerializer 对象使你能够把一个 XML 文档或

  • 在vue中使用dom-top-image,可截取有滚动条的页面,支持多种格式 使用dom-top-image 获取页面png格式截图,并下载到PC, 安装 npm install dom-to-image 在页面中引用 import domtoimage from 'dom-to-image' 使用方法 获取页面dom, 下载到本地本来是用的是window.saveAs,打包后出现未知错误,导

  • 重点:因为 dom-to-image.js 是根据 元素转换svg 进行截图的,所以如果元素有滚动条,他只能截图到 滚动条的顶部,不能截图到对应的滚动条位置 dom-to-image.js 引入         1、下载 yarn add dom-to-image         2、在 node_modules 文件夹中 找到 dom-to-image 文件夹里面的 dom-to-image.j

  •         需求:将dom转成图片,下载到本地。         在实际项目中,有可能会出现这种需求,比如用某字符串生成二维码,然后将二维码打包下载到本地。因为二维码可以是前端来生成(使用插件qrcode.js),所以没有图片链接给到前端,但是页面的二维码实际已经生成,在这种情况下,可以使用dom-to-image来下载。 一、dom-to-image下载一张图片         dom-to

  • 具体场景: 原逻辑:纭毅YMS加注站点信息中有下载二维码的功能,点击后弹出弹窗,原功能下载二维码仅仅下载二维码图片 优化后:业务提出优化需要连同油站以及站点编码一起下载 html2canvas 插件 1. 作用:html2canvas 的作用就是允许让我们直接在用户浏览器上拍摄网页或其部分的“截图” 2. 原理:它的屏幕截图是基于 DOM 的,因此可能不会 100%精确到真实的表示,因为它不会生成

  • 下载必要的js库npm install dom-to-image 引用库import domtoimage from ‘dom-to-image’; ①生成png的图片插入的到当前页面 var node = document.getElementById('my-node'); domtoimage.toPng(node) .then(function (dataUrl) {

  • dom-to-image把dom节点转换为矢量图(svg)和位图(png和jpeg) ,可处理存在滚动条的页面。 前段代码如下: // 导出按钮事件 core.exportPic = function(){ $("#exportExcel").unbind("click").click(function() { // 导出Excel core.post("xls"); }); $("#export

  • 在vue中使用dom-top-image,可截取有滚动条的页面,支持多种格式 具体方法如下: 1.首选安装相关插件 npm install dom-to-image 然后在使用的页面中引用 import domtoimage from 'dom-to-image' 下面是封装的具体的方法: shotPic () { const that = this const n

  • 安装/引入 npm install dom-to-image import domtoimage from 'dom-to-image'; // api toSvg toPng toJpeg toBlob toPixelData domtoimage .toPng(document.querySelector('.box'

 相关资料
  • 以下指令用于将应用程序数据绑定到HTML DOM元素的属性 - Sr.No. 名称和描述 1 ng-disabled 禁用给定的控件。 2 ng-show 显示给定的控件。 3 ng-hide 隐藏一个给定的控件。 4 ng-click 表示AngularJS单击事件。 ng-disabled Directive 将ng-disabled属性添加到HTML按钮并将其传递给模型。 将模型绑定到复选框

  • 在了解DOM(文本对象模型)的框架和节点后,最重要的是使用这些节点处理html网页 对于一个DOM节点node,都有一系列的属性和方法可以使用。常用的有下表。 完善:http://www.w3school.com.cn/xmldom/dom_element.asp 1.访问节点 BOM提供了一些边界的方法访问节点,常用的就是getElementsByTagName(),和getElementByI

  • Shadow DOM 为封装而生。它可以让一个组件拥有自己的「影子」DOM 树,这个 DOM 树不能在主文档中被任意访问,可能拥有局部样式规则,还有其他特性。 内建 shadow DOM 你是否曾经思考过复杂的浏览器控件是如何被创建和添加样式的? 比如 <input type="range">: 浏览器在内部使用 DOM/CSS 来绘制它们。这个 DOM 结构一般来说对我们是隐藏的,但我们可以在开

  • 一、DOM操作影响页面性能的核心问题 通过js操作DOM的代价很高,影响页面性能的主要问题有如下几点: 访问和修改DOM元素 修改DOM元素的样式,导致重绘或重排 通过对DOM元素的事件处理,完成与用户的交互功能 DOM的修改会导致重绘和重排。 重绘是指一些样式的修改,元素的位置和大小都没有改变; 重排是指元素的位置或尺寸发生了变化,浏览器需要重新计算渲染树,而新的渲染树建立后,浏览器会重新绘制受

  • 当我在网上做研究时,似乎人们也在这个堆栈中使用SQS,SNS会将信息放在SQS上,然后SQS会调用Lambda。 我想我想理解的是在这方面对SQS的需求。这增加了什么价值?换句话说,直接从SNS调用我的Lambda会失去什么?

  • dom

    dom 模块用于对 weex 页面里的组件节点进行一部分特定操作。 scrollToElement 将 list 的某个子节点滚动到当前视口 getComponentRect 获取某个组件的 bounding rect 布局信息 addRule 添加 font-face rule getLayoutDirection0.20.0+ 获取某个组件的布局方向(rtl、lrt、inherit) scro