前端页面中可使用JS将整个网页或一部分区域截取成图片并导出。html
今天刚作了一次这个功能,和你们分享一下经验。前端
网页截图的第一步,就是将dom转换图片。目前比较好用的处理方式是先将dom转换成canvas,再从canvas中导出图片。git
可使用html2canvas这个库来实现dom转换成canvas。github
https://github.com/niklasvh/h...canvas
示例代码:浏览器
html2canvas(document.querySelector("#capture")).then(canvas => { document.body.appendChild(canvas) });
canvas展现的时候,自己就有保存为图片的功能。app
若是须要的话,也能够在JS中手动操控。dom
canvas 有两个API能够用来导出图片,分别是 toDataURL 和 toBlobasync
https://developer.mozilla.org...this
https://developer.mozilla.org...
toDataURL能够把canvas导出成图片的data url,toBlob 则是转换成Blob对象,Blob对象能够保存成文件。
若是要在新窗口中展现图片等,使用toDataURL导出的 data url就能够了,而要直接导出成文件的话,使用toBlob更好一些。
调用 canvas.toBlob(),如今咱们有了一个Blob对象,下一步是保存Blob到文件中。
Canvas.toBlob 的文档 https://developer.mozilla.org... 中有提到如何保存Blob到文件,不过使用起来略为复杂。我推荐使用 filesaver 来解决这个问题。参见 https://github.com/eligrey/Fi...
Filesaver 支持保存 canvas 到文件,代码以下:
import { saveAs } from 'file-saver/FileSaver'; canvas.toBlob(function(blob) { saveAs(blob, "pretty image.png"); });
调用 saveAs 以后,浏览器就会执行下载的动做。根据浏览器的设置,可能会直接下载,或弹出保存对话框。
至此,对网页中的一部分进行截图并保存成文件就完成了。
导出的图片基本上会保持原有的样式,只有一小部分不支持。参见 https://html2canvas.hertzen.c...
可是若是截取的范围比较大,那么导出的图片有可能会出现模糊的状况。有多是文字模糊,也有多是图片模糊等。这个时候就须要对图片进行调优
图片调优指的是在 html 导出至 canvas的这个阶段调优,调优方法是修改 html2canvas的参数。
html2canvas(element, options);
调优主要有两个方向:
还有一些其它选项,参见 https://html2canvas.hertzen.c...
最后,附上参考代码:
import { saveAs } from 'file-saver/FileSaver' import html2canvas from 'html2canvas' handleDownloadCapture = async () => { const reportDom = document.querySelector('.report-container') const actualWidth = reportDom.offsetWidth || 1000 const actualHeight = reportDom.offsetHeight || 2000 const factor = 0.6 const canvas = await html2canvas(reportDom, {scale: 1.2, windowWidth: actualWidth * factor, windowHeight: actualHeight * factor}) const filename = this.getExportFilename() canvas.toBlob(blob => saveAs(blob, filename)) }