我们要绘制一张图片,内容包含一张背景图和一个动态天生的二维码,条件是背景图是项目自身的静态资本,二维码是服务端动态天生的,两者不在统一域名下。
解决办法:把一切图片都重定向统一个域名下:
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)
}