Published
Edited
Feb 13, 2022
1 star
Insert cell
Insert cell
Insert cell
{
const ctx = DOM.context2d(width, height);
growTree(ctx, width/2, height-16, height/4, 8, -Math.PI/2);
return ctx.canvas;
}
Insert cell
function growTree(ctx, x1, y1, length, width, angle) {
const x2 = x1 + (Math.cos(angle) * length);
const y2 = y1 + (Math.sin(angle) * length);
drawBranch(ctx, x1, y1, x2, y2, width);
if (length > 1.5) {
const nextLength = () => length * (0.7 + (random() * 0.05));
const angleChange = () => Math.PI / (4 + (random() * 3));
growTree(ctx, x2, y2, nextLength(), width * 0.8, angle + angleChange());
growTree(ctx, x2, y2, nextLength(), width * 0.8, angle - angleChange());
}
}
Insert cell
function drawBranch(ctx, x1, y1, x2, y2, width) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.strokeStyle = `rgba(${Math.round(random() * 80)},100,30,0.8)`;
ctx.stroke();
ctx.closePath();
}
Insert cell
random = d3.randomLcg(seed);
Insert cell
width = 640
Insert cell
height = 512
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