基于html2canvas实现页面截图

108 阅读1分钟

基于html2canvas实现页面截图,兼容A4纸打印~

背景

需求点 需要将 DOM 真是元素内容转换为图片,并且直接下载,npm地址如下:

www.npmjs.com/package/htm…

安装html2canvas

npm i html2canvas -S

基础使用

import html2canvas from 'html2canvas';
import { Message } from 'element-ui';

// 经过调试 A4纸宽度为600,各自业务自行调整
const printWidth = 600;

/**
 * 当前样式是兼容A4纸
 * @param { dom } 截图的元素
 */ 
export function downloadDomToImage(dom) {
	html2canvas(dom, {
		backgroundColor: '#ffffff',
		useCORS: true,
		scale: 5,
		width: printWidth,
		height: dom.scrollHeight,
		windowHeight: dom.scrollHeight,
		allowTaint: true,
	})
		.then(res => {
			const url = res.toDataURL('image/png', 2.0);
			const a = document.createElement('a');
			a.href = url;
			a.download = `截图${window.moment().format('YYYYMMDDHHmmss')}.png`;
			a.click();
			Message.success('截图成功');
		})
		.catch(() => {
			Message.error('截图失败');
		});
}

往期内容

点击链接查看:www.yuque.com/chuxin-cs/i…