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.
contextis 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
_isGlobalstarts out false). However in global modethiswill always be the browser'swindowobject :((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
if (document.readyState === 'complete') { _globalInit(); } else { window.addEventListener('load', _globalInit , false); }var _globalInit = function() { if (!window.PHANTOMJS && !window.mocha) { // If there is a setup or draw function on the window // then instantiate p5 in "global" mode if((window.setup && typeof window.setup === 'function') || (window.draw && typeof window.draw === 'function')) { new p5(); } } };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
// If the user has created a global setup or draw function, // assume "global" mode and make everything global (i.e. on the window) if (!sketch) { this._isGlobal = true; // Loop through methods on the prototype and attach them to the window for (var p in p5.prototype) { if(typeof p5.prototype[p] === 'function') { var ev = p.substring(2); if (!this._events.hasOwnProperty(ev)) { window[p] = p5.prototype[p].bind(this); } } else { window[p] = p5.prototype[p]; } } // Attach its properties to the window for (var p2 in this) { if (this.hasOwnProperty(p2)) { window[p2] = this[p2]; } } } else { // Else, the user has passed in a sketch closure that may set // user-provided 'setup', 'draw', etc. properties on this instance of p5 sketch(this); }trueto _isGlobal. >:)laughed hell hard. Thanks for the explanation @blindfish and @GoToLoop. Really appreciate it. \m/