Help understanding Instance mode vs "normal mode"

please format code with </> button * homework policy * asking questions

So i dont understand why to use instance mode. First i thought that putting “myContainer” i could add class and css position and integrate in a html page with other divs.
But recently i read about cnv.class, cnv.elt and i dont see why to use instance mode.

let cnv = createCanvas(600,400);

then in css file:

#small {
left: 40px;
border: solid;

thanks in advance

first of all please use </> button to format your code. Also I suggest changing the category as Processing is for Java library :slight_smile:

What you are trying to do can be, indeed, done without instance mode. Here you can find some functions - for example, parent can set the parent div of the element (canvas) and style can directly set CSS style.

The reason why there is instance mode is that the default mode is not flexible enough to accommodate several sketches in one code. You cannot simply write two setup functions to create two sketches because the second one simply overwrites the first one. With instance mode, you can separate them in two different scopes and run as two independent sketches.

Also the default mode has a problem that it “contaminates” the global scope. You can use functions like createCanvas, background, and hundreds of them without specifying the scope at the cost of exposing everything to the global scope. This is ok as long as you use p5.js alone, but if you combine with other libraries, they may want to use the same name. Imagine, for example, another library X wants to define a function called background. Then it will be confusing if background belongs to p5.js or X. In fact, if you try to do so, p5.js will warn you like this:

p5 had problems creating the global function “background”, possibly because your code is already using that name as a variable. You may want to rename your variable to something else.

By the way, the normal or default mode is called “global mode”.


I have edit the initial post with your suggestions.
I thought as i wrote only two or three lines of code wasnt necessary to format it.

So the usual and normal mode is global mode.
Then if i can get confussions with other libraries or i need more than one sketch in same html page then you should use instance mode. Am i right ?

Thanks for your help

Yes exactly!

(I would format the code even if it’s just one line because it won’t take you more than a few seconds to format and it makes so much easier for the readers :slight_smile: )

1 Like