Access properties of a sketch's container in instance mode

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();
}
1 Like

Let’s say you’ve got some “style.css” file similar to this 1:

.sketchDiv {
  width: 300px; height: 200px;
}

You can access the sketch’s main canvas via its hidden variable: canvas:

From there, you can access its most immediate parent container via: parentElement:

So far, those are translated as: const parentDiv = p.canvas.parentElement;

Now we can access parentDiv’s dimensions via its offsetWidth & offsetHeight properties:


Now you can call p5::createCanvas() using those 2 dimensions:

p.setup = function () {
  const parentDiv = p.canvas.parentElement;
  p.createCanvas(parentDiv.offsetWidth, parentDiv.offsetHeight);

  // ...
};
2 Likes

Wow, thanks so much @GoToLoop! That worked for me. I would never have found that out by myself.

One question though, why do you use const and not var or let? I tried it with var and it worked just the same.

There are 5 keywords that can be used to declare a variable in JS: :key:

  1. var
  2. let
  3. const
  4. function
  5. class

Here’s the reference for const btW: :innocent:

2 Likes

Here is a breakdown of var vs let vs const and their scopes:

http://www.constletvar.com/

Const also cannot be reassigned.

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.

1 Like