dom-to-image 和 html2canvas
dom-to-image 配置没 html2canvas 多,但是兼容性好一点,不会有生成的和页面不一样的情况,html2canvas 会因为一些 css 样式不支持,搞出来的奇丑
1.html2canvas
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| // 引入html2canvas import html2canvas from 'html2canvas' // id 为导出节点ID imgName 导出文件名称 export function getImg(id, imgName) { var getPixelRatio = function (context) { // 获取设备的PixelRatio var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 0.5; return (window.devicePixelRatio || 0.5) / backingStore; }; //生成的图片名称 var imgNameStr = `${imgName}.jpg`; var shareContent = document.getElementById(id); var width = shareContent.offsetWidth; var height = shareContent.offsetHeight; var canvas = document.createElement("canvas"); var context = canvas.getContext('2d'); var scale = getPixelRatio(context); //将canvas的容器扩大PixelRatio倍,再将画布缩放,将图像放大PixelRatio倍。 canvas.width = width * scale; canvas.height = height * scale; canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; context.scale(scale, scale);
var opts = { scale: 1, background: '#FFFFFF' }; window['pageYoffset'] = 0; document.documentElement.scrollTop = 0; document.body.scrollTop = 0; html2canvas(shareContent, opts).then((canvas) => { context.imageSmoothingEnabled = false; context['webkitImageSmoothingEnabled'] = false; context['msImageSmoothingEnabled'] = false; context.imageSmoothingEnabled = false; var dataUrl = canvas.toDataURL('image/jpeg', 1.0); dataURIToBlob(imgNameStr, dataUrl, callback); }); }
function dataURIToBlob(imgName, dataURI, callback) { var binStr = atob(dataURI.split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
for (var i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); }
callback(imgName, new Blob([arr])); }
function callback(imgName, blob) { let a = document.createElement('a') a.setAttribute("href", URL.createObjectURL(blob));
a.setAttribute("download", imgName); a.onclick = function () { if (navigator.msSaveBlob) { return navigator.msSaveBlob(blob, imgName); } } document.body.appendChild(a) a.click(); a.remove(); };
|
2.dom-to-image(推荐)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import domtoimage from 'dom-to-image' import FileSaver from 'file-saver';
export function createImage(id, name) { let node = document.getElementById(id); let that = this domtoimage.toPng(node) .then(function (dataUrl) { console.log(dataUrl) // that.dataUrl = dataUrl FileSaver.saveAs(dataUrl, name || '流程图片.png'); }) .catch(function (error) { console.error('生成失败', error); }); }
|