場景描述:
在H5頁面需要生成截圖,用於分享給其他用戶。可以通過開源庫html2canvas實現這一功能。
官方文檔
github -> https://github.com/niklasvh/html2canvas
使用文檔 -> http://html2canvas.hertzen.com/documentation
安裝
//這裏最好指定安裝版本,原因見下文
npm i [email protected]
使用
import html2canvas from 'html2canvas';
generateShareImage() {
const canvas = document.createElement("canvas")
let canvasBox = document.getElementById('imageWrapper')
const width = canvasBox.offsetWidth
const height = canvasBox.offsetHeight
canvas.width = width * 2
canvas.height = height * 2
// 生成頁面模糊時,可以放大一定倍數,通過調整canvas的寬高使其清晰度增加
// const context = canvas.getContext("2d");
// context.scale(1.5, 1.5);
const options = {
backgroundColor: null,
canvas: canvas,
useCORS: true
};
html2canvas(canvasBox, options).then((canvas) => {
let dataURL = canvas.toDataURL("image/png");
//下載
this.downloadImage(dataURL);
//顯示
var share = document.getElementById('shareImg');
share.src = dataURL;
})
},
downloadImage(url) {
let link = document.createElement("a");
link.href = url;
link.setAttribute("download", "截圖.png");
link.click();
},
踩坑記錄
1、截圖區域存在網絡圖片時,會有跨域問題
解決方法:
(1) 將圖片放置服務器,通過nginx進行代理資源,前端訪問圖片便不涉及到跨域問題
(2) 使用base64圖片傳輸,base64太大不便於傳輸的話,讓後端寫一個接口,上傳圖片base64數據返回圖片地址
2、在ios微信13.4.1上,出現無法截圖的情況
微信社區帖子:https://developers.weixin.qq.com/community/develop/doc/00006eee95488060bb1ac5bd85b000
解決方法:換用1.0.0-rc.4版本。注意,要先把1.0.0-rc.5卸載了再裝1.0.0-rc.4纔有效
npm uninstall html2canvas
npm i [email protected]
3、截圖尺寸需要適配,不同容器上可能截圖大小不一致。
4、其他
可能個別標籤屬性支持不夠,不過我沒碰到。
關於截圖清晰度不夠的問題,可以通過調整canvas來提高清晰度,若效果不明顯,推薦另一個庫 https://github.com/tsayen/dom-to-image,該庫的清晰度比html2canvas高一些,不過對於標籤屬性的支持可能現在比不上html2canvas,畢竟這個庫好幾年沒更新了,有時會出現截圖失敗的情況。
另外,分享兩篇不錯的博客