Some place like this 1?
p5.js sketches can use 2 approach coding styles: “Global” & “Instance” modes.
On “global mode” the whole p5 instance is dumped in the window global context.
While on “instance mode” we create a function containing our sketch code and pass it as the 1st argument for the p5 constructor.
“Global mode” is the easiest to code with. However, we can’t have more than 1 “Global mode” sketch running on the same frame context!
If we need to have more than 1 sketch, we’re gonna have to code the others on “instance mode” style.
Unless we place the extra “global mode” sketches on their own separate <iframe>
tag:
Developer.Mozilla.org/en-US/docs/Web/HTML/Element/iframe
On the link below we’ve got 4 sketch instances on the same page:
Matter-JS-Bouncing-Colorful-Balls.Glitch.me/all.html
The top 2 are coded w/ “global mode” style, while the 2 on the bottom are using “instance mode”:
Matter-JS-Bouncing-Colorful-Balls.Glitch.me/sketches/global.mjs
Matter-JS-Bouncing-Colorful-Balls.Glitch.me/sketches/instance.mjs
If you hit CTRL+U on the 4 running sketches’ page you’re gonna come up w/ the following “all.html” file:
<script defer src=https://cdn.JsDelivr.net/npm/p5></script>
<script defer src=https://cdn.JsDelivr.net/npm/matter-js></script>
<iframe src=global.html></iframe>
<script type=module src=sketches/global.mjs></script>
<script type=module>
import sketch from '/sketches/instance.mjs';
for (let i = 0; i++ < 2; new p5(sketch));
</script>
Notice I had to place the extra “global mode” sketch in an <iframe>
, b/c we can’t have more than 1 “global mode” sharing the same page frame:
<iframe src=global.html></iframe>
It loads another HTML file, which in turn loads & runs “global.mjs” along w/ p5.js & matter-js libraries, separated from its parent HTML’s context:
Matter-JS-Bouncing-Colorful-Balls.Glitch.me/global.html
<script defer src=https://cdn.JsDelivr.net/npm/p5></script>
<script defer src=https://cdn.JsDelivr.net/npm/matter-js></script>
<script type=module src=sketches/global.mjs></script>
In short we can stick w/ the easier “global mode” style as long as we take care to place them in separate <iframe>
tags if we’re using more than 1 global sketch on the same page.