anne
June 30, 2022, 1:51pm
1
How does one pass on the context to a callback in p5?
fx in this code, the x i undefined:
function setup() {
createCanvas(400, 400);
noLoop()
}
function draw() {
background(128);
let x = 100;
loadImage(“birch.png”, imageLoaded)
}
function imageLoaded(img){ //this function could be called whatever we want
image(img,x,200,100,100);
}
best
anne
mnse
June 30, 2022, 3:49pm
2
Hello @anne ,
would you open up a bit more and give an example in your question of what you actually want to do? Then we could maybe help you much better!
Cheers
— mnse
1 Like
Hi @anne
Try declaring x at the top of the program. I would use
var x;
because I’ve not caught up with the ‘let’ fashion. Where you have let x = 100; just have
x = 100;
Think that fixes what you asked, but as well as that, think your imageLoaded definition should not have a parameter “(img)” . Suggest you see the reference for loadImage . The syntax is different from yours.
1 Like
Use preload() to load assets.
1 Like
I should have said, that having to use a global variable is messy, but in JavaScript I don’t know how else to do it.
You can avoid needing to create global variables by using instance mode.
Try the following:
new p5((p) => {
let x = 100;
let img;
p.preload = () => {
img = p.loadImage("birch.png");
};
p.setup = () => {
p.createCanvas(400, 400);
};
p.draw = () => {
p.image(img,x,200,100,100);
};
});
See this reference material:
1 Like
anne
July 1, 2022, 10:34am
7
Thank you for answering my question!
1 Like