Skip to content

Instantly share code, notes, and snippets.

@kadamwhite
Last active August 29, 2015 13:56
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 kadamwhite/8867646 to your computer and use it in GitHub Desktop.
Save kadamwhite/8867646 to your computer and use it in GitHub Desktop.
Options for instantiating P5

P5 Instance Creation Options

Automatic Instantiation

function setup() {
	rect( 0, 0, 100, 100 );
}

function draw() {
	// ...
}

Advantages: Closest to experience of using the processing IDE; easy for beginners to get started Disadvantages: Requires every P5 method to be global; may be challenging to go from global-everything to a more modular approach (that's the issue Angular faces)

Note: It would theoretically be possible to do something like this:

<script src="p5.min.js"></script> <script type="p5"> rect( 0, 0, 100, 100 ); </script>
>
> However, I don't think that's advisable: it would require a lot of special-case code, and (if we have a goal to encourage P5 users to take advantage of web best-practices) would sort of miss the point. Specific IDEs can implement this kind of implicit mode in their editors, but that would be outside the scope of p5.js proper.

## Define `setup` and `draw` within a function (Processing.js-style)

```javascript
// `p` is a P5 instance object
function sketchProcedure( p ) {
  p.setup = function() {
    rect( 0, 0, 100, 100);
  };

  p.draw = function() {
    // ...
  };
}

// Instantiate, creating a new context
var pInstance = P5( sketchProcedure );

// Instantiate and bind to an existing context
// (what "context" really means is TBD -- canvas, DOM container, etc)
P5( ctx, sketchProcedure );

Advantages: Compatibility with the existing Processing.js style; Disadvantages: functionArgument.method = function syntax is confusing;

Object Configuration

P5({
  setup: function() {
    rect( 0, 0, 100, 100 );
  },
  draw: function() {
    // ...
  }
});

@kadamwhite
Copy link
Author

By Default (implicit instance)

function setup() {
  rect( 0, 0, 100, 100 );
}
// A canvas is created, with context "window"
// A rectangle is drawn on that canvas
// events are bound to the window

Explicit Instance

<div id="sketch"></div>
// option 1
var instance = P5( 'sketch', {
  setup: function() {
    rect( 0, 0, 100, 100 );
});
// option 2
var context = document.getElementById('sketch');
var instance = P5( context, {
  setup: function() {
    rect( 0, 0, 100, 100 );
  }
});

There's two reveals:
0. For a beginner, the instance is invisible

  1. You define an instance, and now you can refer to a canvas by reference
  2. You can have multiple canvases, referring to each by reference

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