看到 TJ 大神 star了dom-to-image,也一直很好奇html
怎么转 image
javascript
那么就翻下源码,看下是如何实现的,其实一共就不到800行代码,还蛮容易读懂的css
使用svg
的一个特性,容许在<foreignobject>
标签中包含任意的html
内容。(主要是 XMLSerializer | MDN这个api
将dom
转为svg
)
因此,为了渲染那个dom
节点,你须要采起如下步骤:html
clone
原始的 dom
节点computed style
,并将这些样式添加进新建的style标签中(不要忘记了clone 伪元素的样式)@font-face
data:
URLS引用css rules
所有都放进<style>
中,并把标签加入到clone的节点中去<img>元素
svg
<foreignobject>
标签中,放入svg
中,而后将其做为data: url
uint8array
获取,使用svg做为源建立一个img
标签,并将其渲染到新建立的canvas
上,而后把canvas
转为base64
import domtoimage from 'dom-to-image'
domtoimage 有以下一些方法:java
* toSvg (`dom` 转 `svg`) * toPng (`dom` 转 `png`) * toJpeg (`dom` 转 `jpg`) * toBlob (`dom` 转 `blob`) * toPixelData (`dom` 转 像素数据)
见名知意,名字取得很是好node
下面我挑一个toPng
来简单解析一下原理,其余的原理也都是相似的git
尽可能挑最核心的讲,但愿不会显得很繁琐,了解核心思想就好
下面介绍几个核心函数:github
调用顺序为canvas
toPng 调用 Draw Draw 调用 toSvg toSvg 调用 cloneNode
toPng方法:api
// 里面其实就是调用了 draw 方法,promise返回的是一个canvas对象 function toPng(node, options) { return draw(node, options || {}) .then(function (canvas) { return canvas.toDataURL(); }); }
Draw方法promise
function draw(domNode, options) { // 将 dom 节点转为 svg(data: url形式的svg) return toSvg(domNode, options) // util.makeImage 将 canvas 转为 new Image(uri) .then(util.makeImage) .then(util.delay(100)) .then(function (image) { var canvas = newCanvas(domNode); canvas.getContext('2d').drawImage(image, 0, 0); return canvas; }); // 建立一个空的 canvas 节点 function newCanvas(domNode) { var canvas = document.createElement('canvas'); canvas.width = options.width || util.width(domNode); canvas.height = options.height || util.height(domNode); ...... return canvas; } }
toSvg方法
function toSvg (node, options) { options = options || {} // 设置一些默认值,若是option是空的话 copyOptions(options) return ( Promise.resolve(node) .then(function (node) { // clone dom 树 return cloneNode(node, options.filter, true) }) // 把字体相关的csstext 所有都新建一个 stylesheet 添加进去 .then(embedFonts) // clone 处理图片啊,background url('')里面的资源,顺便加载好 .then(inlineImages) // 把option 里面的一些 style 放进stylesheet里面 .then(applyOptions) .then(function (clone) { // node 节点序列化成 svg return makeSvgDataUri( clone, // util.width 就是 getComputedStyle 获取节点的宽 options.width || util.width(node), options.height || util.height(node) ) }) ) // 设置一些默认值 function applyOptions (clone) { ...... return clone } }
cloneNode 方法
function cloneNode (node, filter, root) { if (!root && filter && !filter(node)) return Promise.resolve() return ( Promise.resolve(node) .then(makeNodeCopy) .then(function (clone) { return cloneChildren(node, clone, filter) }) .then(function (clone) { return processClone(node, clone) }) ) // makeNodeCopy // 若是不是canvas 节点的话,就clone // 是的话,就返回 canvas转image的 img 对象 function makeNodeCopy (node) { if (node instanceof HTMLCanvasElement) { return util.makeImage(node.toDataURL()) } return node.cloneNode(false) } // clone 子节点 (若是存在的话) function cloneChildren (original, clone, filter) { var children = original.childNodes if (children.length === 0) return Promise.resolve(clone) return cloneChildrenInOrder(clone, util.asArray(children), filter).then( function () { return clone } ) // 递归 clone 节点 function cloneChildrenInOrder (parent, children, filter) { var done = Promise.resolve() children.forEach(function (child) { done = done .then(function () { return cloneNode(child, filter) }) .then(function (childClone) { if (childClone) parent.appendChild(childClone) }) }) return done } } // 处理添加dom的css,处理svg function processClone (original, clone) { if (!(clone instanceof Element)) return clone return Promise.resolve() // 读取节点的getComputedStyle,添加进css中 .then(cloneStyle) // 获取伪类的css,添加进css .then(clonePseudoElements) // 读取 input textarea 的value .then(copyUserInput) // 设置svg 的 xmlns // 命名空间声明由xmlns属性提供。此属性表示<svg>标记及其子标记属于名称空间为“http://www.w3.org/2000/svg”的XML方言 .then(fixSvg) .then(function () { return clone })
下面是这篇的重点 把html
节点序列化成svg
// node 节点序列化成 svg function makeSvgDataUri (node, width, height) { return Promise.resolve(node) .then(function (node) { node.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml') // XMLSerializer 对象使你可以把一个 XML 文档或 Node 对象转化或“序列化”为未解析的 XML 标记的一个字符串。 // 要使用一个 XMLSerializer,使用不带参数的构造函数实例化它,而后调用其 serializeToString() 方法: return new XMLSerializer().serializeToString(node) }) // escapeXhtml代码是string.replace(/#/g, '%23').replace(/\n/g, '%0A') .then(util.escapeXhtml) .then(function (xhtml) { return ( '<foreignObject x="0" y="0" width="100%" height="100%">' + xhtml + '</foreignObject>' ) }) // 变成svg .then(function (foreignObject) { return ( '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">' + foreignObject + '</svg>' ) }) // 变成 data: url .then(function (svg) { return 'data:image/svg+xml;charset=utf-8,' + svg }) }