canvas因為圖片資源不在同一域名下而導致的跨域汙染畫布的解決辦法

不會飛的Porco發表於2019-02-16

我們要繪製一張圖片,內容包括一張背景圖和一個動態生成的二維碼,前提是背景圖是專案本身的靜態資源,二維碼是服務端動態生成的,二者不在同一域名下。

解決辦法:把所有圖片都重定向同一個域名下:

let count = 0;
let bgImg = document.creatElement(`img`);
let qrImg = document.creatElement(`img`);
bgImg.src = redirectUrl(`x.png`);
qrImg.src = redirectUrl(`y.png`);
[bgImg, qrImg].forEach((e) => {
    e.onload = () => {
        count ++;
        if (count === 2) {
            drawerImg(bgImg, qrImg);  
        }
    }
})
function redirectUrl (url) {
    return `https://xxx/view?fileUrl=` + encodeURIComponent(url);
}
function drawerImg (imgContent, qrContent, scaleBy = 2) {
    let {bgImgW, bgImgH} = {375, 800};
    let {qrx, qry, qrw, qrh} = {20, 700, 50, 50};
    let Canvas = document.createElement(`canvas`);
    let ctx = Canvas.getContext("2d");
    Canvas.width = bgImgW * scaleBy;
    Canvas.height= bgImgH * scaleBy;
    ctx.drawImage(imgContent, 0, 0, bgImgW * scaleBy, bgImgH * scaleBy);
    ctx.drawImage(qrContent, qrx * scaleBy, qry * scaleBy, qrw * scaleBy, qrh * scaleBy);
    
    let nodeI = document.createElement("img");
    nodeI.src = Canvas.toDataURL();
    document.body.appendChild(nodeI)
}


相關文章