Skip to content

Instantly share code, notes, and snippets.

@lmccart
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmccart/9399632 to your computer and use it in GitHub Desktop.
Save lmccart/9399632 to your computer and use it in GitHub Desktop.
p5 sketch instance options
// Note: all of these are demonstrating the implicit version where
// no canvas or div is specified, and one is automatically generated.
// With all of these it would be possible to also pass in a node.
// Option 1: sketch is obj created and run by p5
var sketch = new P5.createSketch();
sketch.gray = 0;
sketch.setup = function() {
this.createCanvas(600, 400);
this.background(this.gray);
};
sketch.draw = function() {
this.rect(this.width/2, this.height/2, 200, 200);
};
sketch.mousePressed = function() {
this.gray += 10;
};
P5.run(sketch); // P5.run(sketch, canvasElement);
// Option 2: functionally equivalent to option 1,
// but using "sketch" syntax instead of "this"
var sketch = new P5.createSketch();
sketch.gray = 0;
sketch.setup = function() {
sketch.createCanvas(600, 400);
sketch.background(sketch.gray);
};
sketch.draw = function() {
sketch.rect(sketch.width/2, sketch.height/2, 200, 200);
};
sketch.mousePressed = function() {
sketch.gray += 10;
};
P5.run(sketch); // P5.run(sketch, canvasElement);
// Option 3: passing a function
P5(function( sketch ) {
var gray = 0;
sketch.setup = function() {
this.createCanvas(600, 400);
this.background(gray);
};
sketch.draw = function() {
this.rect(this.width/2, this.height/2, 200, 200);
}
sketch.mousePressed = function() {
gray += 10;
}
});
// Option 4: functionally equivalent to option 3,
// but using "sketch" syntax instead of "this"
P5(function( sketch ) {
var gray = 0;
sketch.setup = function() {
sketch.createCanvas(600, 400);
sketch.background(gray);
};
sketch.draw = function() {
sketch.rect(sketch.width/2, sketch.height/2, 200, 200);
}
sketch.mousePressed = function() {
gray += 10;
}
});
// Option 5: passing an object
P5({
gray: 0,
setup: function() {
this.createCanvas(600, 400);
this.background(this.gray);
},
draw: function() {
this.rect(this.width/2, this.height/2, 200, 200);
},
mousePressed: function() {
this.gray += 10;
}
});
@REAS
Copy link

REAS commented Mar 6, 2014

I read through these extremely quickly to get an immediate reaction. Option 2 was the clearest from my point of view. I'll read through them more carefully now.

@REAS
Copy link

REAS commented Mar 6, 2014

OK, for what it's worth, I still feel that Option 2 is the way I'd like to teach it and think about it.

@REAS
Copy link

REAS commented Mar 8, 2014

For the record, we've been won over by Option 4 and its variant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment