base64保存下载图片
1 exportPng() { 2 let _this = this; 3 let option = _this.charts.getOption(); 4 5 console.log(option); 6 // 从echarts获取图片 7 let imgData = _this.charts.getDataURL({ 8 type: "png", 9 pixelRatio: 2, 10 backgroundColor: '#000', 11 excludeComponents: ['toolbox', 'dataZoom'], 12 }); 13 _this.downloadFile(`${_this.chartsData.name}.png`, imgData); 14 }, 15 // 下载 16 downloadFile(fileName, content) { 17 let aLink = document.createElement('a'); 18 let blob = this.base64ToBlob(content); //new Blob([content]); 19 20 let evt = document.createEvent("HTMLEvents"); 21 evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为 22 aLink.download = fileName; 23 aLink.href = URL.createObjectURL(blob); 24 25 // aLink.dispatchEvent(evt); 26 //aLink.click() 27 aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐 28 }, 29 //base64转blob 30 base64ToBlob(code) { 31 let parts = code.split(';base64,'); 32 let contentType = parts[0].split(':')[1]; 33 let raw = window.atob(parts[1]); 34 let rawLength = raw.length; 35 36 let uInt8Array = new Uint8Array(rawLength); 37 38 for (let i = 0; i < rawLength; ++i) { 39 uInt8Array[i] = raw.charCodeAt(i); 40 } 41 return new Blob([uInt8Array], {type: contentType}); 42 },
摘抄CSDN博文,以此记录供自己使用!
“如果命运是一条孤独的河流,谁会是你的灵魂摆渡人?”