目前主流的兩種方式網(wǎng)頁生成圖片的插件
Install NPM
npm install --save html2canvas
Install Yarn
yarn add html2canvas
引入方式ES6
import html2canvas from "html2canvas";
常見問題:
- 出現(xiàn)滾動條,只截取到可視區(qū)域的頁面
解決方法: 克隆一個需要生成圖片的DOM對象
//解決截屏時,滾動條隱藏部分不能截取問題
const tableWidth = this.$refs.custom_table.$refs.cTable.bodyWidth; // 具體內(nèi)容的寬度
const tableHeight = this.$refs.custom_table.clientHeight; // 具體內(nèi)容的高度
const targetDom = document.querySelector(".imgArea");
let copyDom = targetDom.cloneNode(true);
copyDom.style.width = tableWidth;
copyDom.style.height = tableHeight;
document.querySelector("body").appendChild(copyDom);
調(diào)用方法生成圖片下載
// options 參數(shù)設(shè)置參照文檔說明
const options = { useCORS: true, backgroundColor: null }
html2canvas(copyDom,options ).then(
canvas => {
//document.body.appendChild(canvas);
this.imgURL = canvas.toDataURL("image/png");
//必須同源(訪問的網(wǎng)站域名與服務(wù)器域名一致)才能下載
const eleLink = document.createElement("a");
eleLink.href = this.imgURL; // 轉(zhuǎn)換后的圖片地址
eleLink.download = +new Date() + "_實時采集數(shù)據(jù)";
document.body.appendChild(eleLink);
// 觸發(fā)點擊
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
document.body.removeChild(copyDom);
}
);
具體用法點擊 插件名稱進入到官方有使用樣例。
出現(xiàn)滾動條和html2canvas解決方式一樣
domtoimage.toJpeg(copyDom).then(function(dataUrl) {
const eleLink = document.createElement("a");
eleLink.href = dataUrl; // 轉(zhuǎn)換后的圖片地址
eleLink.download = +new Date() + "_實時數(shù)據(jù).jpeg";
document.body.appendChild(eleLink);
// 觸發(fā)點擊
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
});