我正在 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;
}
编辑在阅读我的代码几个小时后,我终于明白发生了什么:
this.componetsJSON = loadJSON(componetsJSON, () => this.components = this.createComponets());
这个想法是在加载 JSON 之后,方法 createComponents 加载不同的图像。
最佳答案
如果您的代码有问题,则从您发布的极小部分中看不到。很可能问题在于您如何加载图像或使用生成的 p5.Graphics
实例。这是一个工作示例,我用一个简单的用例填补了空白:
const boxSize = 1;
let components;
let gameMap;
function preload() {
// We need to load images in preload to make sure they are available when we're drawing them
let tree = loadImage('https://www.paulwheeler.us/files/tree.png');
components = [{
img: loadImage('https://www.paulwheeler.us/files/game_map.png'),
x: 0,
y: 0,
width: 200,
height: 200
},
{
img: tree,
x: 20,
y: 100,
width: 56,
height: 70
},
{
img: tree,
x: 120,
y: 20,
width: 56,
height: 70
}
];
}
function setup() {
createCanvas(windowWidth, windowHeight);
gameMap = createGameMapImg();
}
function draw() {
let size = min(width, height);
image(gameMap, 0, 0);
}
function createGameMapImg() {
let gameImg = createGraphics(width * boxSize, height * boxSize);
gameImg.background(color('white'));
for (let component of components) {
// I'm not sure why this was in your code, since it looked
// like the goal was to draw the images to the cameImg
// graphics object:
// image(component.img, component.x * boxSize, component.y * boxSize, component.width * boxSize, component.height * boxSize);
if (component.img != undefined) {
gameImg.image(
component.img,
component.x * boxSize,
component.y * boxSize,
component.width * boxSize,
component.height * boxSize
);
}
}
return gameImg;
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.3.1/lib/p5.js"></script>
关于javascript - 在 P5.js 中合并图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67490356/