利用html2canvas将DOM生成图片并下载

607 阅读1分钟
import html2canvas from "html2canvas"
/* 利用html2canvas将DOM生成图片并下载
*  参数:
*  refDom:需要转为图片DOM结构的ref
*  imageName:生成并下载的图片名称,默认年月日时分秒
*  scale:图片缩放比例,默认不缩放
*  imageType下载图片格式,默认png格式weuh 
*  backgroundColor:图片背景色,默认白色 注:透明色传nul
*/
export function domRefToImage(refDom, imageName = null, scale = 1, imageType = "image/png", backgroundColor = '#fff') {
	if (imageName === null) {
	   let nowDate = new Date()
	   imageName = '' + nowDate.getFullYear() + (nowDate.getMonth() + 1) + nowDate.getDate() + nowDate.getHours() + nowDate.getMinutes() + nowDate.getSeconds()
	}
	const canvas = document.createElement("canvas")
	const width = parseInt(window.getComputedStyle(refDom).width)
	const height = parseInt(window.getComputedStyle(refDom).height)
	canvas.width = width * scale
	canvas.height = height * scale
	canvas.style.width = width + 'px'
	canvas.style.height = height + 'px'
	const ctx = canvas.getContext("2d");
	ctx.scale(scale, scale);
	const options = {
	   backgroundColor,
	   canvas,
	   useCORS: true
	}
	html2canvas(refDom, options).then((canvas) => {
	   let a = document.createElement('a')
	   a.href = canvas.toDataURL(imageType)
	   a.download = imageName
	   a.click()
	})
}