我们要绘制一张图片,内容包括一张背景图和一个动态生成的二维码,前提是背景图是项目本身的静态资源,二维码是服务端动态生成的,二者不在同一域名下。
解决办法:把所有图片都重定向同一个域名下:
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)
}