Published
Edited
May 1, 2021
2 forks
Insert cell
Insert cell
Insert cell
Insert cell
canvas = {
const context = DOM.context2d(width, height);
context.fillStyle = "#ffffff";
context.clearRect(0, 0, width, height);

context.canvas.id = "main-canvas";

return context.canvas;
}
Insert cell
Insert cell
d3.select("#main-canvas").on("click", e => {
const [x, y] = d3.pointer(e);
addBall({ x, y });
})
Insert cell
Insert cell
init = {
const tick = () => {
requestAnimationFrame(tick);

simulation.clearCanvas();
simulation.tick();
};

tick();
}
Insert cell
Insert cell
Insert cell
Insert cell
class Ball {
constructor({ id, x, y, radius, angle, speed, color, ctx }) {
this.id = id;
this.x = x || 10;
this.y = y || 10;
this.pos = [x ,y];
this.radius = radius || d3.randomUniform(3, 9)();
this.mass = radius * radius;
this.angle = angle || d3.randomUniform(0, 360)();
this.speed = speed || d3.randomUniform(1, maxSpeed)();
this.color = color || d3.schemeCategory10[Math.round(d3.randomUniform(0, 9)())];
this.ctx = ctx || null;
}

drawCircle() {
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
this.ctx.fillStyle = this.color;
this.ctx.stroke();
this.ctx.fill();
}

tick() {

[this.x, this.y] = this.pos = geometric.pointTranslate(this.pos, this.angle, this.speed);
// this.x += 0.1*this.speed;
// this.y += 0.1*this.speed;
}
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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