问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
function handleShow(visible: boolean) {
arr.bgW = props.tempArray.config.size[0];
arr.bgH = props.tempArray.config.size[1];
if (visible) {
loading.value = true;
setModalProps({ loading: true, confirmLoading: true });
setTimeout(() => {
setModalProps({ loading: false, confirmLoading: false });
nextTick(() => {
let canvas = myCanvas.value;
let context = canvas.getContext('2d');
canvas.width = props.tempArray.config.size[0];
canvas.height = props.tempArray.config.size[1];
let contBox = props.tempArray.config.data;
arr.imgList = [];
arr.textList = [];
contBox.forEach((item) => {
if (item.type == 'img') {
arr.imgList.push(item);
} else {
arr.textList.push(item);
}
});
imgList(arr.imgList, context, canvas);
});
loading.value = false;
}, 1000);
}
}
const loadImg = (url, context) => {
return new Promise((resolve) => {
var image;
image = new Image();
// image.crossOrigin = 'Anonymous';
let itemImg = url.src;
var timestamp = new Date().getTime();
if (itemImg.indexOf('http') != -1) {
image.src = itemImg + '?' + timestamp;
} else {
image.src = arr.bgUrl + itemImg + '?' + timestamp;
}
if (image.width <= 0 && image.height <= 0) {
context.font = '24px STheiti, SimHei';
context.fillText('图片加载失败无法进行绘制,请稍后再次或者更换图片', 10, 166);
}
image.onload = () => {
resolve(image);
};
image.onerror = () => {
reject(`Errors on loading`);
};
});
};
const imgList = (list, context, canvas) => {
const imgQueue = [];
for (let i = 0; i < list.length; i++) {
imgQueue.push(loadImg(list[i], context));
}
Promise.all(imgQueue).then((item) => {
item.crossOrigin = 'Anonymous';
for (var i in item) {
if (item[i] != 'Anonymous') {
context.drawImage(item[i], list[i].x, list[i].y, list[i].width, list[i].height);
}
// 图片绘制
}
console.log(item);
arr.textList.forEach((itemList) => {
// 绘制文字
textList(itemList, context, canvas);
});
console.log(canvas);
var dataURL = canvas.toDataURL(); //得到图片的base64编码数据
console.log(dataURL);
});
console.log(22);
};
function textList(res, context) {
var bold;
if (res.bold) {
bold = 'bold';
} else {
bold = 'normal';
}
context.font = `normal ${bold} ${res.fontsize}px sans-serif`; // console.log(ctx.font);
context.fillStyle = res.color;
var y = (res.y + res.y + res.height) / 2 + res.fontsize / 2;
var metrics = context.measureText(res.value); // console.log(metrics);
var x;
if (res.width < metrics.width) {
x = res.x;
} else {
x = res.x + (res.width - metrics.width) / 2;
}
context.fillText(res.value, x, y);
}
运行结果及报错内容
我的解答思路和尝试过的方法
1.item.crossOrigin = 'Anonymous';
2.在路径后面添加随机数
我想要达到的结果
输出base64