准备工作
导入框架
"canvas-toBlob": "^1.0.0", // yarn add canvas-toBlob or npm install canvas-toBlob --save
"file-saver": "^2.0.2", // yarn add file-saver or npm install file-saver --save
"html2canvas": "^1.0.0-rc.5", // yarn add html2canvas or npm install html2canvas --save
"jquery": "^1.0.0-rc.5", // yarn add jquery or npm install jquery --save
工具封装 domToImage.js
import html2canvas from 'html2canvas';
import FileSaver from 'file-saver';
import $ from 'jquery';
import 'canvas-toBlob';
function clickTarget(target) {
const { userAgent } = navigator;
if (userAgent.includes('Firefox')) {
const event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
target.dispatchEvent(event);
} else {
target.click();
}
}
function dataURLtoBlob(dataUrl) {
const arr = dataUrl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n) {
n -= 1;
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
/**
* 传入适合参数将html生成图片(适配IE)
* @param {*} params
* node: 需要生成图片的html标签
* pngName: 导出的图片名称
* shouldNotDownload:是否不需要将生成的图片下载到电脑,默认false
* responseResultMethod:执行方法的结果回调 resultCode: 200 成功
*/
function html2canvasToImage(params) {
const {
node,
pngName,
shouldNotDownload,
responseResultMethod,
} = params;
if (!node) {
throw new Error('节点不存在');
}
const option = {
allowTaint: true, // Whether to allow cross-origin images to taint the canvas
useCORS: true, // Whether to attempt to load images from a server using CORS
};
html2canvas(node, option).then(canvas => {
if (shouldNotDownload) {
if (responseResultMethod) responseResultMethod({ resultCode: 200, canvas });
} else {
canvas.toBlob(blob => {
FileSaver.saveAs(blob, `${pngName || 'html2canvas'}.png`);
if (responseResultMethod) responseResultMethod({ resultCode: 200, blob });
});
}
}).catch(error => {
console.error('html2canvas', error);
if (responseResultMethod) responseResultMethod({ resultCode: 110, error });
});
}
/**
* 已知canvas或dataUrl将其以图片形式导出(适配IE)
* @param {*} params
* canvas: canvas值
* dataUrl: dataUrl值
* imageName: 导出的图片名称
* responseResultMethod:执行方法的结果回调 resultCode: 200 成功
*/
function useCanvasOrDataUrlDownlodImage(params) {
const {
canvas,
dataUrl,
imageName,
responseResultMethod,
useATag, // 使用a标签下载图片
} = params;
if (!canvas && !dataUrl) {
throw new Error('canvas或dataUrl不存在');
}
//
const fileName = `${imageName || 'html2canvas'}.png`;
if (useATag) {
if (!!window.ActiveXObject || 'ActiveXObject' in window) {
const blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, fileName);
} else {
const url = canvas.toDataURL();
// 以下代码为下载此图片功能
clickTarget($(`<a href="${url}" download="${fileName}"></a>`)[0]);
}
} else if (dataUrl && !canvas) {
const blob = dataURLtoBlob(dataUrl);
FileSaver.saveAs(blob, fileName);
if (responseResultMethod) responseResultMethod({ resultCode: 200 });
} else {
canvas.toBlob(blob => {
FileSaver.saveAs(blob, fileName);
if (responseResultMethod) responseResultMethod({ resultCode: 200, blob });
});
}
}
export {
html2canvasToImage,
useCanvasOrDataUrlDownlodImage,
};
如何使用
import { html2canvasToImage } from 'domToImage';
const params = {
node: this.contentContainerRef,
pngName: '图片名称',
shouldNotDownload: false,
responseResultMethod: response => {
console.log(response);
},
};
html2canvasToImage(params);
网友评论