因业务需求,后端返回二维码和中间logo图地址,前端上传海报背景实现海报拼装并下载
function drawPoster(imgList, otherInfo) {
const drawImg = (resolve, imgList, otherInfo, oldContext, oldCanvas) => {
const { url = '', width = 280 * 4, height = 496 * 4, x = 0, y = 0 } = imgList[0];
const image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.onload = () => {
if (oldContext && oldCanvas) {
oldContext.drawImage(image, x, y, width, height);
imgList.shift();
if (imgList.length) {
drawImg(resolve, imgList, otherInfo, oldContext, oldCanvas);
} else {
resolve({ url: oldCanvas.toDataURL('image/png'), ...otherInfo });
}
} else {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
context.drawImage(image, x, y, width, height);
imgList.shift();
if (imgList.length) {
drawImg(resolve, imgList, otherInfo, context, canvas);
} else {
resolve({ url: canvas.toDataURL('image/png'), ...otherInfo });
}
}
};
image.src = url + (url.indexOf('?') > -1 ? '&time=' : '?time=') + new Date().valueOf();
};
return new Promise((resolve, reject) => drawImg(resolve, imgList, otherInfo));
}