I’ve made a P5 sketch in instance mode. Now, I wanted to get to know some of the settings from it’s parent element. Like dimensions.
For this I thought a good starting point would be to be able to know who is it’s parent. Doing a console.log( sketch ); I found out it has the id in the sketch object. sketch.canvas.parentElement.id.
This is my abstracted sketch. As you can see I actually create two sketches.
var p5Back = function( sketch ) {
console.log( sketch );
let parentDivId = sketch.canvas.parentElement.id;
console.log( parentDivId );
}
let sketch_01 = new p5( p5Back, ‘sketch_01’ );
let sketch_02 = new p5( p5Back, ‘sketch_02’ );
But this last console.log prints TypeError: sketch.canvas is undefined
The canvas is created at the beginning of setup so it’s undefined when you line of code runs. You’ll have to run it after the after createCanvas() happens in setup. There’s an implicit createCanvas(100, 100) at the beginning of setup if you don’t put one in.
Try something like:
const p5Back = function(sketch) {
sketch.setup = function() {
let parentDivId = sketch.canvas.parentElement.id;
console.log(parentDivId); // prints "" which is the id of the body element
}
}
Check out the parent() documentation for a more streamlined approach to getting and setting a parent.
Yes!, that’s it. Placing it inside setup did the trick.
Ah yes, I’ll take a look at the documentation. It was the wiki page where I found out about the instance mode in the first place.