Multiple p5.js sketches in separate divs on one HTML page

Let's say you want to have multiple sketches on a single page, how do you do it? P5.js is the answer but the solution is not straight forward. This page explains the process. This is not an intro to p5.js or HTML.



The first trick is to separate your sketches using “instance mode". This way the sketches can be referenced in different divs, yet still be the same file. Brennan Pilcher added a instance mode option to the Processing to P5.js page we made, if you want to get a head start.
The next trick is to use 'var' to send the sketch to the html (not 'new' as in some examples), and to put the id of the div where you want the canvas to be created inside single 'quotes' after the name of the instance variable like this: var myp5 = new p5(s, 'divName');
Here's examples of the P5.js and the corresponding HTML. Of course you will also need a libraries folder with the p5.js file in the same directory as these two files. You can get it from the p5.js website.

The p5.js

 
// save this file as sketch.js
// Sketch One
var s = function( p ) { // p could be any variable name
  var x = 100; 
  var y = 100;
  p.setup = function() {
    p.createCanvas(400, 200);
  };

  p.draw = function() {
    p.background(0);
    p.fill(255);
    p.rect(x,y,50,50);
  };
};
var myp5 = new p5(s, 'c1');

// Sketch Two
var t = function( p ) { 
  var x = 100.0; 
  var y = 100; 
  var speed = 2.5; 
  p.setup = function() {
    p.createCanvas(400, 200);
  };

  p.draw = function() {
    p.background(100);
    p.fill(1);
    x += speed; 
    if(x > p.width){
      x = 0; 
    }
    p.ellipse(x,y,50,50);

  };
};
var myp5 = new p5(t, 'c2');

The html

<html>
<head>
	<meta charset="UTF-8">
	<script language="javascript" type="text/javascript" src="libraries/p5.js"></script>
	<!-- uncomment lines below to include extra p5 libraries -->
	<!-- 	<script language="javascript" src="libraries/p5.dom.js"></script> -->
	<!--<script language="javascript" src="libraries/p5.sound.js"></script>-->
	<script language="javascript" type="text/javascript" src="sketch.js"></script>
	<!-- this line removes any default padding and style. you might only need one of these values set. -->
	<style> body {padding: 0; 
		margin: 0;
	} 
</style>
</head>
<body>
	<div id="c1"></div> <br>
	<div id="c2"></div>
</body>
</html>
Back to Joe McKay home page