Published
Edited
Jun 13, 2021
Insert cell
Insert cell
Insert cell
Insert cell
p5(sketch => {
let bubble1, bubble2;

sketch.setup = function() {
sketch.createCanvas(width, 400);
//sketch.frameRate(8); // Change frame rates per second!

// Create instances of the bubble class:
bubble1 = new Bubble(200, 200, 20);
bubble2 = new Bubble(400, 200, 60);
};

sketch.draw = function() {
sketch.background(0);

bubble1.move();
bubble1.show();
bubble2.move();
bubble2.show();
};

// Class:
class Bubble {
// Just once. Specifies how the object is initialised
constructor(itemX, itemY, itemR) {
this.x = itemX;
this.y = itemY;
this.r = itemR;
}

// Class methods
move() {
this.x = this.x + sketch.random(-5, 5);
this.y = this.y + sketch.random(-5, 5);
}
show() {
sketch.stroke(255);
sketch.strokeWeight(4);
sketch.noFill();
sketch.circle(this.x, this.y, 24);
}
}
})
Insert cell
Insert cell
Insert cell
Insert cell
function* p5(sketch) {
const element = DOM.element('div');

// p5.js really likes its target element to already be in the DOM, not just
// floating around detached. So, before we call P5, we yield it, which puts
// in the DOM.
yield element;

// This is ‘instance mode’ in p5 jargon: instead of relying on lots of
// globals, we create a sketch that has its own copy of everything under p5.
const instance = new P5(sketch, element, true);

// This is the tricky part: when you run P5(sketch, element), it starts a
// loop that updates the drawing a bunch of times a second. If we were just
// to call P5 repeatedly with different arguments, the loops would all keep
// running, one on top of the other. So what we do is we use this cell
// as a generator, and then when that generator is interrupted, like
// when you update the code in the sketch() method, then we call instance.remove()
// to clean it up.
try {
while (true) {
yield element;
}
} finally {
instance.remove();
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more