实现
import html2canvas from 'html2canvas';
const downloadImage = (filename = 'snapshoot', imageUrl = null) => {
if (!imageUrl) {
throw '缺少图片地址!';
}
const DA = document.createElement('a');
DA.download = (filename || 'snapshoot') + '.png';
DA.href = imageUrl;
document.body.appendChild(DA);
DA.click();
DA.remove();
};
const Snapshoot = (element, filename = 'snapshoot') => {
if (!element) {
throw '缺少元素!';
}
const canvas = document.createElement('canvas');
const width = parseInt(window.getComputedStyle(element).width);
const height = parseInt(window.getComputedStyle(element).height);
canvas.width = width * 4;
canvas.height = height * 4;
const options = {
canvas,
useCORS: true,
allowTaint: true,
tainttest: true,
logging: false,
scrollX: 0,
scrollY: 0,
scale: 4,
dpi: window.devicePixelRatio * 4,
};
html2canvas(element, options).then((canvas) => {
const dataURL = canvas.toDataURL('image/png');
downloadImage(filename, dataURL);
});
};
export default Snapshoot;
使用
const element = document.getElementById('snapshoot');
Snapshoot(element, '截图');