React 生成分享海报,html2canvas的使用
使用html2canvas生成页面或指定dom节点的截图,并下载到本地。
1.安装html2canvas
npm i html2canvas --save
2.使用html2canvas生成截图的base64
html2canvas详细配置参考:https://allenchinese.github.io/html2canvas-docs-zh-cn/docs/html2canvas-configuration.html
简单示例代码如下:
import html2canvas from "html2canvas";
export default () => {
const saveImage = () => {
html2canvas(document.getElementById("image")).then(canvas => {
const imageBase64 = canvas.toDataURL("image/png"); // 得到base64
// 下载到本地
const a = document.createElement("a");
a.src= imageBase64;
a.addAttribute("download");
// 模拟点击事件
var evt = document.createEvent('Event');
evt.initEvent("click",true,true);
a.dispatchEvent(evt);
});
}
return <div>
<div id="image">需要生成截图的节点<div>
<button onClick={saveImage}>分享</div>
</div>
}
问题记录
1、图片跨域解决方案
设置配置项 allowTaint: false, canvas 的 CanvasRenderingContext2D 属于浏览器的对象,如果渲染过跨域资源,浏览器就认定 canvas 已经被污染了 Taint:污点
设置配置项 useCORS: false,表示允许跨域资源共享,注意不能与 allowTaint 同时配置为 true
img 标签中添加 crossOrigin = "anonymous", anonymous:如果使用这个值的话就会在请求 header 中带上 Origin 属性,但请求不会带上 cookie 和客户端 ssl 证书等其他的一些认证信息
图片服务器配置 Access-Control-Allow-Origin: *, 重要的配置项,是跨域问题的根本源泉,需要后端配合
2、截图锯齿解决方案
根据设备像素比进行缩放
// 设置放大倍数
const scale = window.devicePixelRatio;
3、截图不全解决方案
截图之前将页面滚动到顶部或者将元素全部展示出来不用滚动条
document.body.scrollTop = document.documentElement.scrollTop = 0;
const imgBlobData = await convertToImage(element);