Published
Edited
Dec 6, 2019
3 forks
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
// Constants controlling simulation
const radius = 5;
const startX = 200;
const startY = 200;
const stepSize = 2*radius;
//const stepDur = 100; // Now controlled by slider above
const trailColor = 'lightblue';
const trailOpacity = .2;
// Create the SVG container for sim
const svg_actual = DOM.svg(400, 400)
const svg = d3.select(svg_actual);
// Create an empty circle to indicate where walk began
const startingPoint = svg.append('circle')
.attr('cx', startX)
.attr('cy', startY)
.attr('r', radius)
.style('stroke', 'black')
.style('fill', 'white');
// Here's our happy walking circle!
let walker = svg.append('circle')
.attr('cx', startX)
.attr('cy', startY)
.attr('r', radius)
.style('fill', 'black');
// Function to run a single "step" of the random walk
// (and kick off the *next* step)
function step() {
// Choose a direction
let axis = Math.random() < .5 ? 'cx' : 'cy';
let dir = Math.random() < .5 ? -1*stepSize : stepSize;
// Animate circle's movement in that direction
walker
.transition()
.attr(axis,parseInt(walker.attr(axis))+dir)
.duration(stepDur)
.delay(stepDur)
.on('end', step); // Once animation is done, kick off another step!
// For each step, drop a new circle with low opacity
// to create a "trail" showing where we've been.
svg.insert('circle',':first-child') // walker should stay on top
.attr('cx', walker.attr('cx'))
.attr('cy', walker.attr('cy'))
.attr('r', radius)
.style('fill', trailColor)
.style('opacity', trailOpacity);
}
// Kick off the animation!
step();
return svg_actual;
}
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