简介
通过 html2canvas 可以实现截取屏幕中显示内容,并生成图片下载下来。
安装
npm install --save html2canvas
安装插件
引入
import html2canvas from "html2canvas";
在需要引入的页面进行引入
使用
对需要截图的区域设置id
<div id='test' style={{ textAlign: "center",padding:'20px 0' }}>
<div style={{ textAlign: 'center', fontSize: 18 }}>{item.teacherTenantName}邀请您加入评课</div>
<div style={{ color: '#a9a9a9', fontSize: '15px', marginTop: 10 }}>
<div>{item.appraiseTitle}</div>
<div>
<span>授课教师:</span><span>{item.teacherName}</span>
</div>
<div ><span>开始时间:</span><span>{moment(item?.startTime).format("YYYY-MM-DD dddd HH:mm")}</span></div>
<div ><span>授课单位:</span><span>{item.teacherTenantName}</span></div>
<div ><span>课程时长:</span><span>{item.duration}分钟</span></div>
<div>
<span>评课人员:</span><span>{evaluatorObj[item.appraiseTeacherStudentStatus].desc}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'center', margin: '20px 0px' }}>
<QRCode id="qrEl" value={qrcodeUrl} size={100} fgColor="#000000" />
</div>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Space size="large">
<Button type="default" onClick={() => { onDownload(item.appraiseTitle) }}>
下载
</Button>
<Button type="primary" onClick={copy}>复制链接</Button>
</Space>
</div>
</div>
</div>
调用函数
const onDownload = (title) => {
html2canvas(document.getElementById('test')).then((canvas) => {
const link = document.createElement("a");
link.href = canvas.toDataURL();
link.setAttribute("download", title + ".png");
link.style.display = "none";
document.body.appendChild(link);
link.click();
});
// setDownloadUrl(url)
}
效果
将整个div 下载下来了!