I have a problem with the fillRect
canvas function: I use the setFillStyle
function to either set the fillStyle
to a rgb value or to an image source.(我的fillRect
画布函数有问题:我使用setFillStyle
函数将fillStyle
设置为rgb值或图像源。)
The image will be fetched using the image's onload
method.(图像将使用图像的onload
方法获取。) Since I want to make sure that the following call to fillRect
will be using this fillStyle
I made it return a promise and I set its caller to async
and awaiting setFillStyle
.(由于我想确保对fillRect
的以下调用将使用此fillStyle
我使它返回了一个setFillStyle
并将其调用者设置为async
并等待setFillStyle
。)
It appears that fillRect
ignores the await
since sometimes (when the image doesn't get fetched in time) it draws a #000000
color (which is default) over the entire canvas while sometimes (when the image luckily gets fetched in time) it draws the pattern generated of the image.(似乎fillRect
忽略了await
因为有时(当图像没有及时获取时)它会在整个画布上绘制#000000
颜色(默认),而有时(当幸运地及时获取图像时)会绘制图像生成的图案。)
async fillArea() {
const { width, height } = this.context.canvas;
await this.setFillStyle()
.catch(({ src }) => console.error(`Failed to load image: ${src}`));
this.context.fillRect(0, 0, width, height);
},
setFillStyle() {
const { type, value = '', src = '', repeat = '' } = this.hideOptions;
this.context.globalCompositeOperation = 'source-over';
if (type === 'color') return this.context.fillStyle = value;
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve({ src });
img.onerror = () => reject({ src });
img.src = src;
this.context.fillStyle = this.context.createPattern(img, repeat);
});
},
I also tried to not use async await
and fall back to .then
which didn't lead to a different behavior:(我还尝试不使用async await
并回退到.then
这不会导致其他行为:)
fillArea() {
const { width, height } = this.context.canvas;
this.setFillStyle()
.catch(({ src }) => console.error(`Failed to load image: ${src}`))
.then(() => this.context.fillRect(0, 0, width, height));
},
How can this be resolved since I can't get my head around it?(由于我无法解决这个问题,该如何解决?)
ask by SUBHUMAN translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…