I'm making a game on p5.js and I want to Merge the image of each component to get the background of the game, but using createGraphics doesn't work. Here is the code:
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;
}
After reading my code for hours I finally understand what was happening:
this.componetsJSON = loadJSON(componetsJSON, () => this.components = this.createComponets());
The idea is after load the JSON the method createComponents load the diferent images.
Description. Draw an image to the p5. js canvas. This function can be used with different numbers of parameters.
If there is something wrong with your code it is not evident from the very minimal fraction you posted. Most likely the issue is with how you are loading the images or using the resulting p5.Graphics
instance. Here is a working example where I've filled in the blanks with a simple use case:
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/[email protected]/lib/p5.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With