We are about to switch to a new forum software. Until then we have removed the registration on this forum.
INSTANCE MODE
var sketch = function( p ) {
var x = 100;
var y = 100;
p.setup = function() {
p.createCanvas(700, 410);
};
p.draw = function() {
p.background(0);
p.fill(255);
p.rect(x,y,50,50);
};
};
var myp5 = new p5(sketch);
GLOBAL MODE
var x = 100;
var y = 100;
function setup() {
createCanvas(200,200);
}
function draw() {
background(0);
fill(255);
ellipse(x,y,50,50);
}
I have run through the source of p5.js but I am not sure how it works in both modes(global and instance) and how it detects which mode the user is using. I guess it has to do something with instance object _pInst which gets passed through p5.Element. Also in functions we find -
var ctx = this._pInst || this;
So my guess it that it takes for both cases in this OR statement.
Please correct me on this if I am wrong.
Answers
The answer is in core.js.
context
is assigned either to window or the containing object... The latter is far more sane - polluting the global scope is bad practice - though then requires a reference to the container to access p5 methods/properties.Edit: Note that at first run context is always assigned to the 'containing object' (since
_isGlobal
starts out false). However in global modethis
will always be the browser'swindow
object :((In instance mode it's the p5 object instantiated with
new p5(sketch);
https://GitHub.com/processing/p5.js/blob/master/src/app.js#L71
https://GitHub.com/processing/p5.js/blob/master/src/core/core.js#L37
var p5 = function(sketch, node, sync) {
https://GitHub.com/processing/p5.js/blob/master/src/core/core.js#L450
true
to _isGlobal. >:)laughed hell hard. Thanks for the explanation @blindfish and @GoToLoop. Really appreciate it. \m/