Callback context

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);

function draw() {

let x = 100;
loadImage(“birch.png”, imageLoaded)

function imageLoaded(img){ //this function could be called whatever we want


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!

— 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 = () => {

See this reference material:

1 Like

Thank you for answering my question!

1 Like