Creating Multiples with p5.js
In this workshop, we will look at how to create multiples using for-loops and objects as well as looking at some methods of enhancing the style of our visuals. To review the basics of p5.js, please read over content from this previous workshop.
Example 1: Bouncing balls
Click on canvas to create balls and press space bar to make them move again:
The overall structure of the example is that every time mouse is pressed 5 more ellipses are created. Note that I say 5 more, because the canvas still draws the ellipses that were generated before. For this example, we will be mainly focusing on how objects can be used with for-loops and arrays so that multiple objects can be created and updated.
First, let's create our Circle class, which will contain the attributes and behaviors of our "balls" or "circles" that appear when we mousepress.
function Circle(x, y){ this.x = x; this.y = y; this.dia = 50; this.display = function(){ fill(255, 255, 255); ellipse(this.x, this.y, this.dia, this.dia); } }
Above code is for creating the class we name Circle, and it takes 2 arguments when created. This means, when we create a new object of class Circle, we would say:
var c = new Circle(200, 300);
Example 2: Spinning balls
Click on canvas to create spinning balls:
Click to view the demo as a full web page.
Example 3: Waves
Move the mouse vertically to change the height of the waves:
Click to view the demo as a full web page.