第一步安装 html2canvas 依赖
npm i html2canvas
第二步 创建canvas获取dom内容,然后使用html2canvas生成图片
/*** @name 生成截图* @param {Element} canvasBox 截图区域dom对象*/
export const createScreenshot = (canvasBox, down = true) => {return new Promise((resolve,reject) => {// 手动创建一个 canvas 标签const canvas = document.createElement('canvas')// 获取父级的宽高const width = parseInt(canvasBox.width)const height = parseInt(canvasBox.height)// 宽高 * 2 并放大 2 倍 是为了防止图片模糊canvas.width = width * 2canvas.height = height * 2canvas.style.width = width + 'px'canvas.style.height = height + 'px'const context = canvas.getContext('2d')context.scale(2, 2)html2canvas(canvasBox, {allowTaint: true}).then((canvas) => {//转换base64const capture = canvas.toDataURL('image/png', 0.5)//下载浏览器弹出下载信息的属性const date = new Date()const saveInfo = {//导出文件格式自己定义,我这里用的是时间作为文件名download: date.getTime() + `.png`,href: capture,}//下载,浏览器弹出下载文件提示down && downloadFile(saveInfo)resolve(capture)}).catch(err => {reject(err)})})
}
第三步下载所生成的图片
/*** @name 下载文件* @param {Object} saveInfo 下载参数内容*/
export const downloadFile = (saveInfo) => {const element = document.createElement('a')element.style.display = 'none'for (const key in saveInfo) {element.setAttribute(key, saveInfo[key])}document.body.appendChild(element)element.click()setTimeout(() => {document.body.removeChild(element)}, 300)
}