通过html2canvas生成分享图片
什么是 html2canvs?
html2canvas 的作用就是允许让我们直接在用户浏览器上拍摄网页或其部分的“截图”。
它的屏幕截图是基于 DOM 的,因此可能不会 100% 精确到真实的表示,因为它不会生成实际的屏幕截图,而是基于页面上可用的信息构建屏幕截图。所以一个比较常见的应用场景就是我们可以使用它在 H5 端生成分享图。
- 下载
html2canvas官网: http://html2canvas.hertzen.com/
- 使用
//引入改文件
<script src="./js/html2canvas.js"></script>
- 调用
// 获取分享图片 base64function getShareImgBase64 () {return new Promise((resolve) => {setTimeout(() => {// #capture 就是我们要获取截图对应的 DOM 元素选择器html2canvas(document.querySelector('#capture'), {useCORS: true, // 【重要】开启跨域配置scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,allowTaint: true, // 允许跨域图片}).then((canvas) => {const bs64 = canvas.toDataURL('image/jpeg', 1.0);resolve(bs64);});}, 300); // 这里加上 300ms 的延迟是为了让 DOM 元素完全渲染完成后再进行图片的生成});}//通过then接收
getShareImgBase64().then((res) => {console.log(res);
})
注意:生成的图片是bs64格式的,向后端传建议使用form表单直接上传文件
let bytes = window.atob(bs64)
let ab = new ArrayBuffer(bytes.length)
let ia = new Uint8Array(ab)
for (let i = 0; i < bytes.length; i++) {ia[i] = bytes.charCodeAt(i)
}
let imgs = new File([ab], name, { type: 'image/jpg' })
const formData = new FormData()
formData.append('file', imgs)
//此处上传直接使用ajax还,直接把formData放到data那里就行,不需要键值对形势
如果遇到报错:
Error: Failed to execute ‘atob’ on ‘Window’: The string to be decoded is not correctly encoded
错误:无法在’Window’上执行’atob’:要解码的字符串未正确编码
解决办法:将上面报错的那行代码换成下面这种就可以了
let bytes = atob(bs64.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''));
完整的代码:
// 获取分享图片 base64
function getShareImgBase64 () {return new Promise((resolve) => {setTimeout(() => {// #capture 就是我们要获取截图对应的 DOM 元素选择器html2canvas(document.querySelector('#capture'), {useCORS: true, // 【重要】开启跨域配置scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,allowTaint: true, // 允许跨域图片}).then((canvas) => {const bs64 = canvas.toDataURL('image/jpeg', 1.0);let bytes = window.atob(bs64.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''))let ab = new ArrayBuffer(bytes.length)let ia = new Uint8Array(ab)for (let i = 0; i < bytes.length; i++) {ia[i] = bytes.charCodeAt(i)}let imgs = new File([ab], name, { type: 'image/jpg' })resolve({"bs64":bs64,"imgs":imgs});});}, 300); // 这里加上 300ms 的延迟是为了让 DOM 元素完全渲染完成后再进行图片的生成});
}
截图效果: