Published
Edited
Mar 1, 2022
1 star
Insert cell
Insert cell
viewof color = Inputs.color()
Insert cell
Insert cell
chart = {
// Variable that stores whether to show a circle
// Is set by clicking on the SVG
let isCircle = false;

// Variable that stores fill color
// Is set by update function called by update cell below
let fillColor = "black";

// Create SVG
const sel = d3
.create("svg")
.attr("viewBox", "-10 -10 20 20")
.attr("width", 200)
.on("click", () => {
// When you click anywhere on SVG, switch shape and re-render
isCircle = !isCircle;
render();
});

// Create shapes
const circle = sel.append("circle").attr("r", 10);
const rect = sel.append("rect").attr("x", -9).attr("y", -9).attr("width", 18).attr("height", 18);

// Render function sets visibility and fill
function render() {
circle
.attr("visibility", isCircle ? "visible" : "hidden")
.attr("fill", fillColor);
rect
.attr("visibility", !isCircle ? "visible" : "hidden")
.attr("fill", fillColor);
}

// Call render once initially
render();

// Return DOM node with an attached update method,
// which is called by a different cell with the value of the color input
return Object.assign(sel.node(), {
update(value) {
fillColor = value;
render();
}
});
}
Insert cell
Insert cell
update = chart.update(color)
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