【发布时间】:2021-05-12 13:57:26
【问题描述】:
我正在 p5.js 上制作游戏,我想合并每个组件的图像以获得游戏的背景,但是使用 createGraphics 不起作用。代码如下:
createGameMapImg() {
let gameImg = createGraphics(this.width * this.boxSize, this.height * this.boxSize);
gameImg.background(color('white'));
for (let component of this.components) {
image(component.img, component.x * this.boxSize, component.y * this.boxSize, component.width * this.boxSize, component.height * this.boxSize);
if (component.img != undefined) gameImg.image(component.img, component.x * this.boxSize, component.y * this.boxSize, component.width * this.boxSize, component.height * this.boxSize);
}
return gameImg;
}
编辑
阅读我的代码几个小时后,我终于明白发生了什么:
- 我有一个包含所有组件定义的 JSON(包括 URL img)
- 我将此 JSON 发送到管理组件呈现的类。
- 我在预加载时调用构造函数,但组件图像不会加载,除非我这样做:
this.componetsJSON = loadJSON(componetsJSON, () => this.components = this.createComponets());
这个想法是在加载 JSON 之后,方法 createComponents 加载不同的图像。
【问题讨论】:
-
您能说明您是如何定义
this.components和this.boxsize的吗?还有你怎么称呼这个方法的? -
欢迎来到 StackOverflow @Sonya。虽然最好将问题中的代码减少到基本元素,但您确实需要包含足够的代码以使您的问题可重现(请参阅:stackoverflow.com/help/minimal-reproducible-example)。对于 p5js,您几乎应该总是在您的问题中包含一个可运行的 sn-p:stackoverflow.com/questions/67410651/…
-
@Sonya 你直接调用
image(),它在p5的默认画布中呈现:而不是你想呈现到你的p5.Graphics实例中:gameImg.image(...)。 Paul 的详细示例证明了这一点 (+1)
标签: javascript p5.js