P5.js onCanvasCreated?

Hi,

I’m trying to use p5.js as a GUI part. Trying to do like…

function createP5GUI() {
	let f = function(p) {
		p.setup = function() {
			let c = p.createCanvas(500, 50);
		}
	}
	return new p5(f);
}

and use it in DOM like below
but doesn’t work because canvas needs some time to be created.

let gui = createP5GUI();
console.log(gui.canvas) // undefined
document.body.appendChild(gui.canvas) // error

And it’s easy workaround is to wait some time.

let gui = createP5GUI();
setTimeout(function() {
  document.body.appendChild(gui.canvas);
}, 200);

Apparently it’s not good way…I think it should be like

let gui = createP5GUI();
gui.onCanvasCreated = function(e) {
  document.body.appendChild(e.canvas);
}

Does anyone know how to detect if the canvas created?

Cheers…

Hi! I’m sure I’ve encountered this problem before. I think there is no callback so you need to pass that function and execute it in setup…

But if what you want is to set the parent node, you can set it directly in the constructor

2 Likes