javascript - Canvas 的 fillRect 函数忽略等待
问题描述
我对fillRect
canvas 函数有疑问:我使用该setFillStyle
函数将 设置fillStyle
为 rgb 值或图像源。将使用图像的onload
方法获取图像。因为我想确保下面的调用fillRect
将使用 thisfillStyle
我让它返回一个承诺,我将它的调用者设置为async
和 awaiting setFillStyle
。
似乎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);
});
},
我还尝试不使用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));
},
由于我无法解决这个问题,如何解决这个问题?
解决方案
这段代码的问题是我试图在实际获取图像之前创建模式。该createPattern
函数默认使用#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 new Promise(resolve => resolve(this.context.fillStyle = value));
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
this.context.fillStyle = this.context.createPattern(img, repeat);
resolve(img);
};
img.onerror = () => reject({ src });
img.src = src;
});
},
推荐阅读
- sql-server - SQL Server - EF Core - 自定义约束,其中针对 id 的所有标志都必须为假,除了一个
- python - 联合异步迭代器会发生什么?
- apache - 使用 htaccess 在 Apache 2.4.3x 中创建 301 重定向的问题
- javascript - 有没有办法减少与其调用者通信的无限生成器中的产量数量?
- javascript - 切换条带/checkout.js
- sql-server - SQL Server 子字符串(子字符串())
- c++ - 如何使用opengl将颜色应用于三角形
- php - Laravel 5:返回受影响的行数 PGSQL
- javascript - 如何同时使用 jQuery Validate 的 errorPlacement 和 showErrors
- docker - 带有 iptables/netfilter 的 docker macvlan