Public
Edited
Feb 23, 2023
Insert cell
Insert cell
Insert cell
squares
Insert cell
viewof squares = Squares({
height,
width,
values: update(),
easement: d3.easeCubic,
duration: 1000
})
Insert cell
set = (input, values) => {
input.values = values;
input.dispatchEvent(new Event("input"), { bubbles: true });
return values;
}
Insert cell
// takes configuration object for a clickable circle
// returns DOM node with circle element and process() method
Squares = ({ width, height, values, event, easement, duration }) => {
const svg = d3.create("svg").attr("width", width).attr("height", height);
const node = svg.node();

const elements = svg
.selectAll("rect")
.data(values)
.join("rect")
.attr("x", (d) => d.x)
.attr("y", (d) => d.x)
.attr("height", (d) => d.s)
.attr("width", (d) => d.s)
.attr("fill", (d) => d.fill)
.on("click", () => set(node, update(node.values)));

// const element = circle;
const animate = animator({ elements, duration, easement });

return Object.defineProperty(node, "values", {
get: () => values,
set: (newValues) => animate((values = newValues))
});
}
Insert cell
// takes animation configuration parameters: {element, duration, easement}
// returns function that takes {event} and ⚠️ performs animation on event target’s kind
animator = ({ elements, duration, easement }) =>
(values) => {
return values.forEach(({ s, fill, x, y }) => {
const animation = elements.transition().ease(easement).duration(duration);
animation
.attr("height", s)
.attr("width", s)
.attr("fill", fill)
.attr("x", x)
.attr("y", y);
});
}
Insert cell
update = (values) => {
return Array.from(Array(10), (x, index) => ({
s: anyNatural(20, 100),
fill: d3.schemeCategory10[Math.floor(Math.random() * 10)],

// getter structure lets me reference s from other attributes
get x() {
return anyNatural(0, width - this.s);
},
get y() {
return anyNatural(0, height - this.s);
}
}));
}
Insert cell
update()
Insert cell
anyNatural = (min, max) => +(min + (max - min) * Math.random()).toFixed(0)
Insert cell
height = 200
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