Published
Edited
Nov 18, 2018
4 forks
6 stars
Insert cell
Insert cell
canvas = {
const context = DOM.context2d(width, height);
const triangle = polygon(3, radius);
const hexagon = polygon(6, radius);

while (true) {
context.save();
context.clearRect(0, 0, width, height);
context.translate(width / 2, height / 2);

context.beginPath();
drawCircle(context, radius);
drawCircle(context, radius / 2);
context.strokeStyle = "#ccc";
context.stroke();

context.rotate((Date.now() / 60000) % 1 * 2 * Math.PI);

context.beginPath();
drawPolygon(context, 6, radius);
drawPolygon(context, 6, radius / 2);
drawPolygon(context, 3, radius);
context.strokeStyle = "#000";
context.stroke();

context.beginPath();
drawPolygonSpokes(context, 3, radius);
context.strokeStyle = "#00f";
context.stroke();
context.beginPath();
drawPolygonSpokes(context, 6, radius / 2);
context.strokeStyle = "#f00";
context.stroke();

context.restore();
yield context.canvas;
}
}
Insert cell
function polygon(n, radius) {
const polygon = [[0, radius]];
for (let i = 1; i < n; ++i) {
const angle = i / n * 2 * Math.PI;
const x = radius * Math.sin(angle);
const y = radius * Math.cos(angle);
polygon.push([x, y]);
}
return polygon;
}
Insert cell
function drawCircle(context, radius) {
context.moveTo(radius, 0);
context.arc(0, 0, radius, 0, 2 * Math.PI);
}
Insert cell
function drawPolygon(context, n, radius) {
context.moveTo(0, radius);
for (let i = 1; i < n; ++i) {
const angle = i / n * 2 * Math.PI;
const x = radius * Math.sin(angle);
const y = radius * Math.cos(angle);
context.lineTo(x, y);
}
context.closePath();
}
Insert cell
function drawPolygonSpokes(context, n, radius) {
for (let i = 0; i < n; ++i) {
const angle = i / n * 2 * Math.PI;
const x = radius * Math.sin(angle);
const y = radius * Math.cos(angle);
context.moveTo(0, 0);
context.lineTo(x, y);
}
}
Insert cell
function midpoint([x0, y0], [x1, y1]) {
return [(x0 + x1) / 2, (y0 + y1) / 2];
}
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