Get (p5) canvas element when it has loaded

Viewed 1086

I have two scripts, in one of them I have an animation on a p5 canvas, and on another script I do some operation on it.

Script A - p5 animation:

function setup() {
  let canvas = createCanvas(640, 480);
  canvas.id("vizCanvas");
  // ...

}

function draw() {
 // animation ...
}

Script B - doing something with the animation:

const myCanvas = document.getElementById('vizCanvas');
doSomethingWithMyCanvas(myCanvas)

function doSomethingWithMyCanvas(canvas){
    console.log('hello', canvas)
}

view.ejs (~= index.html):

<head>
  <script src="src/scriptA.js" defer></script>
  <script src="src/scriptB.js" defer></script>
</head>
<body>
...
</body>

The problem is that myCanvas is null. When I use the dev console and type test = document.getElementById('vizCanvas') it successfully references it though. I suppose this means that Script B is trying to fetch vizCanvas before it has been created. I would think that the defer keywords in the tag doesn't allow the scripts to be executed until the window has loaded, but that doesn't really work.

I tried to wrap Script B in a window.onload event, like this:

Script B (revision 1)

window.onload = ()=>{
  const myCanvas = document.getElementById('vizCanvas');
  doSomethingWithMyCanvas(myCanvas)

  function doSomethingWithMyCanvas(canvas){
      console.log('hello', canvas)
  }

}

But when this happens, the p5 animations don't actually work anymore. In fact, if I just change Script B to:

Script B (revision 2)

window.onload = () => {
  console.log("hi")
}

the p5 animations will not play! That said, update() in p5 seems to be running and everything, I just don't see anything.

So my question is: how do I fetch the p5 canvas element once it has loaded?

1 Answers

The setup() function doesn't run right away. It runs after p5 sets itself up and then starts calling functions like setup() and draw(). So you're trying to access the canvas before the setup() function has run.

There are a couple ways to get around this:

  1. Call a function from setup() after you create the canvas. That function can be defined in your other script file if you want.
  2. Use instance mode which gives you a bit more control over when p5.js runs.

I would personally go with option 1, but it depends on your context and what you're trying to do.

Related