Published
Edited
Jan 31, 2019
3 forks
41 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
p5(sketch => {
 let a = 0;
   sketch.setup = function() {
sketch.createCanvas(600, 400);
   sketch.background(255);
sketch.rectMode(sketch.CENTER);
};
sketch.draw = function() {
sketch.background(223,0, 0);
// a call to our function written in a cell below named drawCircle.
// Observable automatically keeps track of the objects & variables ;–)
  drawCircle(sketch.width/2,sketch.height/2, 300,sketch);
sketch.translate(sketch.width/2, sketch.height/2);
sketch.rotate(sketch.radians(a));
sketch.strokeWeight(10);
sketch.stroke(255,255,0);
sketch.rect(0,0, 200,200);
a+=0.5;
 };
})
Insert cell
Insert cell
Insert cell
function drawCircle (x,y,d,sketch){
sketch.push();
sketch.stroke(0,0,255);
sketch.strokeWeight(5);
sketch.noFill();
 sketch.ellipse(x,y,d,d);
sketch.pop();
}
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