html2canvas踩坑記錄

記h5頁面轉圖片中遇到的問題

最近由於產品要求,h5頁面在app中展現一個頁面,分享到朋友圈是另一張動態組裝的圖片。記錄一下踩坑的過程。
複製代碼

代碼

<template>
    <div id="demo">
      <img :src="url+'?'+new Date().getTime()" crossOrigin="anonymous">
    </div>
</template>
複製代碼
data() {
    return {
        url: '',    // 跨域圖片地址
        baseUrl: '' // 保存base64地址
    }
}
methods:{
    canvasToImg() {
    let option = {
        allowTaint: true,
        //useCORS: true
    }
        html2canvas(document.getElementById("demo"),option).then(canvas) => {
            document.body.appendChild(canvas)
            this.baseUrl = canvas.toDataURL(canvas) // 將canvas轉化爲base64圖片
        })
    }
}
複製代碼

遇到問題

html2canvas在截取h5頁面的畫面的時候,頁面若是存在請求的跨域圖片,html2canvas會截取不到。
    解決方法:
        一、allowTaint: true和useCORS:true,兩種方式均可以解決跨域問題,兩個有不一樣的區別,使用allowTaint: true會對canvas形成污
        染,致使canvas.toDataURL()方法不能使用,解決方法就是將請求過來的圖片先轉化爲base64圖片,經過url放到image裏面。
        二、useCORS:true,若是使用這個配置,須要在img標籤裏面添加上crossOrigin="anonymous"特性,而且須要給imgUrl加上隨機的時間
        函數。須要注意的是,還須要在後端服務器設置access-control-allow-origin:*;容許資源跨域訪問,前端並設置useCORL:true,才能作到圖片保存
複製代碼
相關文章
相關標籤/搜索