Public
Edited
Apr 10
Insert cell
Insert cell
Insert cell
class FallingShapes {
constructor(width, height) {
this.width = width;
this.height = height;
this.canvasMargin = 120;
this.shapeCount = 150;
this.shapes = [];
this.timer = 0;

// Speed
this.minSpeed = .5;
this.speedRange = .5;
}

tick() {
this.timer += 1;
// Move existing shapes
const newShapes = this.shapes.filter(s => s.y < (this.height + this.canvasMargin))
.map(s => { s.fall(); return s });
// Add new shapes
while (newShapes.length < this.shapeCount) {
newShapes.push(new Shape(this.width, this.height, this.canvasMargin, this.minSpeed, this.speedRange));
}
this.shapes = newShapes;
}

draw(ctx) {
ctx.save()
ctx.clearRect(0, 0, this.width, this.height)
ctx.strokeStyle = "#000";
ctx.lineJoin = "round";
ctx.lineWidth = 2;
for (let shape of this.shapes) {
shape.draw(ctx)
}
}
}
Insert cell
class Shape {
constructor(xRange, yRange, yMargin, minSpeed, speedRange) {
this.x = Math.random() * xRange;
this.y = -yMargin - (Math.random() * (yRange + (2*yMargin)));
this.speed = minSpeed + (Math.random() * speedRange);
let s = Math.floor(Math.random() * shapes.length)
let c = Math.floor(Math.random() * colors.length)
this.shape = shapes[s]
this.color = colors[c]
if (this.shape.type === "path") {
this.rotate = Math.floor(Math.random() * 360)
}
}

fall() {
this.y += this.speed;
}

draw(ctx) {
switch (this.shape.type) {
case "circle":
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.shape.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
break;
case "rect":
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.shape.w, this.shape.h);
ctx.strokeRect(this.x, this.y, this.shape.w, this.shape.h);
break;
case "path":
let pSrc = new Path2D(this.shape.path);
let mat = new DOMMatrix();
mat.translateSelf(this.x, this.y);
mat.rotateSelf(this.rotate);
let p = new Path2D();
p.addPath(pSrc, mat)
ctx.fillStyle = this.color;
ctx.fill(p);
ctx.stroke(p);
break;
}
}
}
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more