Published
Edited
Jan 16, 2020
Insert cell
Insert cell
{
const boxHeight = 300;
const svg = d3.create('svg').attr('viewBox', [0, 0, width, boxHeight]);

// Create an array of random length, from 2 - 10 elements
let arr = [...Array(d3.randomInt(2, 11)())];

function getRgbColor() {
const red = d3.randomInt(1, 256)();
const green = d3.randomInt(1, 256)();
const blue = d3.randomInt(1, 256)();
const alpha = Math.random();
return d3.rgb(red, green, blue, alpha);
}

function getX(r) {
return d3.randomUniform(r, width - r)();
}

function getY(r) {
return d3.randomUniform(r, boxHeight - r)();
}

function getRadius() {
return d3.randomUniform(10, 100)();
}

// Create a new array of objects with random properties:
// radius, x coordinate, y coordinate, and color
const nodes = arr.map(a => {
const r = getRadius();
return {
x: getX(r),
y: getY(r),
r: r,
color: getRgbColor()
};
});

const tr = d3.transition().ease(d3.easeLinear);

function repeat() {
const r = getRadius();
d3.active(this)
.duration(d3.randomInt(1000, 5000))
.style('fill', getRgbColor())
.attr('r', r)
.attr('cx', d => getX(r))
.attr('cy', d => getY(r))
.transition()
.delay(d3.randomInt(1000, 5000))
.on('start', repeat);
}

// Append circles to the SVG element
svg
.selectAll('circle')
.data(nodes)
.join('circle')
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.attr('r', d => d.r)
.attr('fill', d => d.color)
.transition(tr)
.on('start', repeat);

return svg.node();
}
Insert cell
d3 = require('d3', 'd3-random')
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