Web前端之domToImage文档、html标签元素转成图片
MENUDOM to ImageWhat is itInstallationNPMBowerUsageRendering optionsfilterbgcolorheight, widthstylequalitycacheBustimagePlaceholderBrowsersDependenciesSourceTestsHow it worksThings to watch out forAuthorsLicenseDOM to Image[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HzbkhAXc-1690359033652)(https://travis-ci.org/tsayen/dom-to-image.svg?branchmaster)]What is itdom-to-imageis 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.InstallationNPMnpm install dom-to-imageThen load/* in ES 6 */importdomtoimagefromdom-to-image;/* in ES 5 */vardomtoimagerequire(dom-to-image);Bowerbower install dom-to-imageInclude eithersrc/dom-to-image.jsordist/dom-to-image.min.jsin your pageand it will make thedomtoimagevariable available in the global scope.scriptsrcpath/to/dom-to-image.min.js/scriptdomtoimage.toPng(node)//.../scriptUsageAll 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:varnodedocument.getElementById(my-node);domtoimage.toPng(node).then(function(dataUrl){varimgnewImage();img.srcdataUrl;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){varlinkdocument.createElement(a);link.downloadmy-image-name.jpeg;link.hrefdataUrl;link.click();});Get an SVG data URL, but filter out all theielements:functionfilter(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:varnodedocument.getElementById(my-node);domtoimage.toPixelData(node).then(function(pixels){for(vary0;ynode.scrollHeight;y){for(varx0;xnode.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 */pixelAtXYpixels.slice(pixelAtXYOffset,pixelAtXYOffset4);}}});All the functions underimplare not public API and are exposed onlyfor unit testing.Rendering optionsfilterA 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.bgcolorA string value for the background color, any valid CSS color value.height, widthHeight and width in pixels to be applied to node before rendering.styleAn object whose properties to be copied to node’s style before rendering.You might want to check this referencefor JavaScript names of CSS properties.qualityA number between 0 and 1 indicating image quality (e.g. 0.92 92%) of theJPEG image. Defaults to 1.0 (100%)cacheBustSet to true to append the current time as a query string to URL requests to enable cache busting. Defaults to falseimagePlaceholderA 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 imagesBrowsersIt’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.cssTextproperty.Internet Explorer is not (and will not be) supported, as it does not supportSVGforeignObjecttagSafari is not supported, as it uses a stricter security model onforeignObject tag. Suggested workaround is to usetoSvgand render on the server.DependenciesSourceOnly standard lib is currently used, but make sure your browser supports:PromiseSVGforeignObjecttagTestsMost importantly, tests depend on:js-imagediff,to compare rendered and control imagesocrad.js, for theparts when you can’t compare images (due to the browserrendering differences) and just have to test whether the text is renderedHow it worksThere 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 theforeignObjecttag. So, in order to render that DOM nodefor you, following steps are taken:Clone the original DOM node recursivelyCompute the style for the node and each sub-node and copy it tocorresponding cloneand don’t forget to recreate pseudo-elements, as they are notcloned in any way, of courseEmbed web fontsfind all thefont-facedeclarations that might represent web fontsparse file URLs, download corresponding filesbase64-encode and inline content asdata:URLsconcatenate all the processed CSS rules and put them into onestyleelement, then attach it to the cloneEmbed imagesembed image URLs inimgelementsinline images used inbackgroundCSS property, in a fashion similar tofontsSerialize the cloned node to XMLWrap XML into theforeignObjecttag, then into the SVG, then make it adata URLOptionally, 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 canvasDone!Things to watch out forif the DOM node you want to render includes acanvaselement 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.AuthorsAnatolii Saienko, Paul Bakaus (original idea)LicenseMIT

相关新闻

别再把大数据平台当“巨石”了:聊聊云原生时代的大数据平台怎么活得更久

别再把大数据平台当“巨石”了:聊聊云原生时代的大数据平台怎么活得更久

别再把大数据平台当“巨石”了:聊聊云原生时代的大数据平台怎么活得更久 很多做大数据平台的朋友,一开始都会踩一个坑:把平台越做越大,最后大到自己都不敢动。 你有没有见过这样的场景: 一个 Hadoop / Spark 集群撑着公…

2026/7/3 4:44:24 阅读更多 →
系统不出事,才是运维的最高境界:聊聊如何打造“零故障运维系统”

系统不出事,才是运维的最高境界:聊聊如何打造“零故障运维系统”

系统不出事,才是运维的最高境界:聊聊如何打造“零故障运维系统” 作者:Echo_Wish 很多刚做运维的朋友,心里都会有一个误区: 运维的能力,体现在处理故障的速度。 比如: 服务器挂了 5 分钟恢复 数据库崩了 10 分钟修好 集群异常 30 分钟恢复 听起来很厉害,对吧? 但如…

2026/7/5 4:13:56 阅读更多 →
别等故障来了才救火:聊聊如何用 AI 把 SLA 这件事“提前做对”

别等故障来了才救火:聊聊如何用 AI 把 SLA 这件事“提前做对”

别等故障来了才救火:聊聊如何用 AI 把 SLA 这件事“提前做对” 作者:Echo_Wish 做运维时间久了,你会发现一个特别真实的事情: 很多公司嘴上都在说 SLA(Service Level Agreement,服务等级协议), 但真正做到稳定保障的,其实并不多。 为什么? 因为很多团队做 SLA 的…

2026/7/4 16:49:30 阅读更多 →

最新新闻

MetaCodable宏编程入门:快速掌握Swift Codable高级用法

MetaCodable宏编程入门:快速掌握Swift Codable高级用法

MetaCodable宏编程入门:快速掌握Swift Codable高级用法 【免费下载链接】MetaCodable Supercharge Swifts Codable implementations with macros meta-programming. 项目地址: https://gitcode.com/gh_mirrors/me/MetaCodable 想要提升Swift开发效率&#xf…

2026/7/5 15:48:39 阅读更多 →
【信息科学与工程学】【数据中心】【容灾备份】第三十一篇 云数据中心各类CPU计算型业务跨数据中心容灾设计方案

【信息科学与工程学】【数据中心】【容灾备份】第三十一篇 云数据中心各类CPU计算型业务跨数据中心容灾设计方案

一、云数据中心各类CPU计算型业务跨数据中心指标 1. Web应用服务 设计领域 设计子类 特征/函数 参数/指标 用途说明 数据中心内设计 数据中心间设计 网络设计​ 数据中心内网络 1. 负载均衡网络 2. 应用层网络 3. 数据库网络 4. 缓存网络 5. 管理网络 1. 带宽:>…

2026/7/5 15:44:38 阅读更多 →
K-Means 聚类的目标函数:簇内误差平方和

K-Means 聚类的目标函数:簇内误差平方和

1. 什么是 K-Means? K-Means 是一种无监督、迭代式的聚类算法: 给定数据集 {x₁, x₂, …, xₙ} 与预设簇数 K,算法把样本划分为 K 个不相交的簇 C₁, C₂, …, Cₖ,使得同一簇内样本尽可能相似,不同簇间样本尽可能远离…

2026/7/5 15:44:38 阅读更多 →
【信息科学与工程学】计算机科学与自动化——第三十八篇 质量工程 02 云数据中心质量工程

【信息科学与工程学】计算机科学与自动化——第三十八篇 质量工程 02 云数据中心质量工程

云数据中心质量工程体系(规划-评估-测试-验证-交付) 编码 阶段 层级 核心领域 子领域 质量属性/活动 关键交付物/指标 核心方法/工具 评估标准 挑战与风险 1 核心理念 战略层 质量哲学 可靠性即产品 将数据中心可靠性、性能、安全作为可销售、可承诺的服务产品…

2026/7/5 15:42:38 阅读更多 →
net 跨平台也是一句谎言

net 跨平台也是一句谎言

以前很热炒跨平台,主要是由于硅谷挑战微软霸主地位的热情,但是冷静下来后,跨平台往往不是那么一回事。假设你有个软件,所谓的跨平台,你只需要为第二个平台上重新编译一次就行了,这样很难么? c语…

2026/7/5 15:40:38 阅读更多 →
终极指南:如何用CSUR程序化生成系统打造真实城市道路网络

终极指南:如何用CSUR程序化生成系统打造真实城市道路网络

终极指南:如何用CSUR程序化生成系统打造真实城市道路网络 【免费下载链接】CSUR Offline procedural generation of realistic road environments in Cities: Skylines 项目地址: https://gitcode.com/gh_mirrors/cs/CSUR Cities: Skylines Urban Road (CSUR…

2026/7/5 15:38:37 阅读更多 →

日新闻

B站视频下载神器BiliTools:5分钟学会轻松保存任何B站内容

B站视频下载神器BiliTools:5分钟学会轻松保存任何B站内容

B站视频下载神器BiliTools:5分钟学会轻松保存任何B站内容 【免费下载链接】BiliTools A cross-platform bilibili toolbox. 跨平台哔哩哔哩工具箱,支持下载视频、番剧等等各类资源 项目地址: https://gitcode.com/GitHub_Trending/bilit/BiliTools …

2026/7/5 0:03:34 阅读更多 →
威胁模型全解析:从新手入门到实战应用,助你构建安全产品!

威胁模型全解析:从新手入门到实战应用,助你构建安全产品!

威胁模型的陌生现状在忙碌疲惫的一天里,参与了关于混合后量子密码学的讨论,应付端点攻击找茬的人,还参与留言板讨论后,发现“威胁模型”对多数人仍是陌生概念,且多被当作时髦用语。有趣的相关画作有一幅由 Embyr 创作的…

2026/7/5 0:03:34 阅读更多 →
渗透测试入门指南:从零基础到实战环境搭建

渗透测试入门指南:从零基础到实战环境搭建

1. 从“看热闹”到“入门”:我理解的渗透测试到底是什么?每次看到新闻里说某个大公司的数据被“黑”了,或者某个网站被攻击导致服务瘫痪,你是不是和我一样,心里会冒出两个念头:一是“这黑客真厉害”&#x…

2026/7/5 0:07:38 阅读更多 →

周新闻

B站视频下载神器BiliTools:5分钟学会轻松保存任何B站内容

B站视频下载神器BiliTools:5分钟学会轻松保存任何B站内容

B站视频下载神器BiliTools:5分钟学会轻松保存任何B站内容 【免费下载链接】BiliTools A cross-platform bilibili toolbox. 跨平台哔哩哔哩工具箱,支持下载视频、番剧等等各类资源 项目地址: https://gitcode.com/GitHub_Trending/bilit/BiliTools …

2026/7/5 0:03:34 阅读更多 →
威胁模型全解析:从新手入门到实战应用,助你构建安全产品!

威胁模型全解析:从新手入门到实战应用,助你构建安全产品!

威胁模型的陌生现状在忙碌疲惫的一天里,参与了关于混合后量子密码学的讨论,应付端点攻击找茬的人,还参与留言板讨论后,发现“威胁模型”对多数人仍是陌生概念,且多被当作时髦用语。有趣的相关画作有一幅由 Embyr 创作的…

2026/7/5 0:03:34 阅读更多 →
渗透测试入门指南:从零基础到实战环境搭建

渗透测试入门指南:从零基础到实战环境搭建

1. 从“看热闹”到“入门”:我理解的渗透测试到底是什么?每次看到新闻里说某个大公司的数据被“黑”了,或者某个网站被攻击导致服务瘫痪,你是不是和我一样,心里会冒出两个念头:一是“这黑客真厉害”&#x…

2026/7/5 0:07:38 阅读更多 →

月新闻