首先安裝html2canvas
npm install html2canvas --save
然后引入html2canvas
import html2canvas from 'html2canvas'
打印
function downloadFile(fileName, content) { //下載base64圖片
var base64ToBlob = function(code) {
let parts = code.split(';base64,');
let contentType = parts[0].split(':')[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for(let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
};
let aLink = document.createElement('a');
let blob = base64ToBlob(content); //new Blob([content]);
let evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true); //initEvent 不加后兩個參數(shù)在FF下會報錯 事件類型令野,是否冒泡,是否阻止瀏覽器的默認行為
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.click();
};
function save(elemId) {
html2canvas(document.getElementById(elemId), {
allowTaint: false,
useCORS: true,
}).then(canvas => {
//將圖片保存到變量
var image = canvas.toDataURL("image/jpeg");
downloadFile('杭州市風險地圖', image);
});
}
// 調用save方法
引入html2canvas同樣可以去網上找找js文件引入,這里就不提供了:)