How do I access properties of a sketch’s container in instance mode?
I’d like to run multiple sketches in all the div’s with a certain class on a page. And I’d like to make the width of these sketches the same as the with of their div. I do specify the container element when I append the div as a second argument into the p5() constructor. But how can I now access the container element and its properties like width, etc. from within a sketch?
Can someone help me?
Here’s some example code of my situation:
window.onload = function() {
function runAllSketches() {
let sketches = [];
let sketchDivs = document.getElementsByClassName("sketchDiv");
for (var i = 0; i < sketchDivs.length; i++) {
sketches[i] = new p5(sketch, sketchDivs[i]);
}
var sketch = function(p) {
var sketchHeight = 15;
p.setup = function() {
p.createCanvas(<<<here I need to get the container's width>>>, sketchHeight);
}
p.draw = function(){
...
}
runAllSketches();
}
By contrast, in Processing(Java), you create pseudo-global scope with top-level variables in the sketch – and limit scope further by declaring variables inside functions, classes, methods, within loops etc. To create something that cannot be reassigned (like const), you may use final.
The habit of declaring variables as constant can be a form of defensive programming – it helps catch errors if you later accidentally attempt to change a value which you have declared should not change. In some languages constants may also sometimes also have memory management or performance benefits.