使用方法
項目中引入
npm install html2canvas
html代碼
//html代碼 <!-- 把需要生成截圖的元素放在一個元素容器里,設置一個ref --> <div class="image_tofile" ref="imageTofile"> <!-- 這里放需要截圖的元素,自定義組件元素也可以 --> </div> <!-- 如果需要展示截取的圖片,給一個img標簽 --> <img :src="htmlUrl">
js代碼
// 引入html2canvas import html2canvas from 'html2canvas' // 注冊組件 components: { html2canvas }, data () { return { htmlUrl: '' } }, mounted () { // 如果頁面一加載就需要生成圖片,就在mounted里調用方法,給一個setTimeout,保證頁面元素已存在 setTimeout(this.toImage, 500) }, methods: { // 頁面元素轉圖片 toImage () { // 第一個參數是需要生成截圖的元素,第二個是自己需要配置的參數,寬高等 html2canvas(this.$refs.imageTofile, { backgroundColor: null, useCORS: true // 如果截圖的內容里有圖片,可能會有跨域的情況,加上這個參數,解決文件跨域問題 }).then((canvas) => { let url = canvas.toDataURL('image/png') this.htmlUrl = url // 把生成的base64位圖片上傳到服務器,生成在線圖片地址 this.sendUrl() }) }, // 圖片上傳服務器 sendUrl () { // 如果圖片需要formData格式,就自己組裝一下,主要看后台需要什么參數 const formData = new FormData() formData.append('base64', this.company.fileUrl) formData.append('userId', 123) formData.append('pathName', 'pdf') this.$ajax({ url: apiPath.common.uploadBase, method: 'post', data: formData }).then(res => { if (res.code && res.data) { } }) } }
需要注意的有兩點:
1)在當前 VUE 頁面不能引用 zepto.js 會和 html2canvas 有沖突,總之就是截不出來或者有空白,不管是哪個先加載都不行;
2)如果你想截 iframe 里面的頁面,那么加載的頁面必須和當前面在同一個源之中,也就是瀏覽的同源策略,要不然也截不到內容;