基于v-charts的圖表功能實(shí)現(xiàn)的單個(gè)圖表下載功能。
HTML
<div ref="box"></div>
JS
methods : {
doPrint () {
this.createImage();
this.$nextTick(() => {
if (this.$refs.box.innerHTML) {
let PrintContent = document.getElementById('print-content');
let newContent = PrintContent.innerHTML;
let oldContent = document.body.innerHTML;
document.body.innerHTML = newContent;
window.print();
window.location.reload();
document.body.innerHTML = oldContent;
return false;
}
});
},
createImage () {
const canvas = document.getElementsByTagName('canvas')[0];
let image = canvas.toDataURL({
type: "png",
pixelRatio: 2,
backgroundColor: '#fff',//不設(shè)置此項(xiàng)脓杉,導(dǎo)出圖片的底色是黑色
});
//在頁(yè)面中展示
box.innerHTML = '<img src="' + image + '" alt="">';
//下載
this.downloadFile('測(cè)試.png', image);
},
downloadFile(fileName, content) {
let aLink = document.createElement('a');
let blob = this.base64ToBlob(content); //new Blob([content]);
let evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true);//initEvent 不加后兩個(gè)參數(shù)在FF下會(huì)報(bào)錯(cuò) 事件類型辽剧,是否冒泡霉撵,是否阻止瀏覽器的默認(rèn)行為
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
},
//base64轉(zhuǎn)blob
base64ToBlob(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});
}
}