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