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?