1 // 引入htmlcanvas 2 import Vue from 'vue'; 3 import html2canvas from 'html2canvas'; 4 5 Vue.prototype.$html2canvas = html2canvas; 6 7 // 点击保存调用方法 8 handleSavePic(e) { 9 this.bottomDialog = e 10 const width = this.$refs['save-img'].clientWidth 11 const height = this.$refs['save-img'].scrollHeight 12 const self = this 13 14 // 截图不全 备用滚动到顶部方案 15 // window.pageYoffset = 0; 16 // document.documentElement.scrollTop = 0; 17 // document.body.scrollTop = 0; 18 19 this.$html2canvas(this.$refs['save-img'], { 20 backgroundColor: 'red', 21 useCORS: true, 22 23 // 隐藏某个不像被截图的元素 24 ignoreElements:(element)=>{ 25 if(element.id ==='pirntHideButton') 26 return true; 27 }, 28 29 scale: 2, 30 width, 31 height, 32 windowHeight: height, 33 scrollX: 0, 34 35 //移动端截图截不全的解决办法(不兼容ios) 36 // scrollY: -window.scrollY 37 scrollY: -document.documentElement.scrollTop 38 }).then(canvas => { 39 self.imgUrl = canvas.toDataURL(); 41 // console.log(self.imgUrl) 42 self.downloadFile('download.png', self.imgUrl); 43 }); 44 }, 45 46 // 下载图片 47 downloadFile(fileName, content) { 49 // 浏览器 50 const aLink = document.createElement('a'); 51 const blob = this.base64ToBlob(content); 52 const evt = document.createEvent("HTMLEvents"); 53 evt.initEvent("click", true, true); 54 aLink.download = fileName; 55 aLink.href = URL.createObjectURL(blob); 56 aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); 57 58 }, 59 base64ToBlob(code) { 60 const parts = code.split(';base64,'); 61 const contentType = parts[0].split(':')[1]; 62 const raw = window.atob(parts[1]); 63 const rawLength = raw.length; 64 const uInt8Array = new Uint8Array(rawLength); 65 for (let i = 0; i < rawLength; ++i) { 66 uInt8Array[i] = raw.charCodeAt(i); 67 } 68 return new Blob([uInt8Array], { type: contentType }); 69 },