Published
Edited
Feb 19, 2021
Insert cell
md`# Dashed Line animation

Inspired by https://observablehq.com/@mootari/sda-pressure and adapting https://observablehq.com/@onoratod/animate-a-path-in-d3 to make a dashed line look like its moving when you hover over it, but go back to static once you move away.
`
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
// Add the path
const path = svg.append("path")
.attr("d", line(data))
.attr("fill", "none")
.attr("stroke-width", 4)
.attr("stroke-dasharray", 8 + " " + 4)
.attr("stroke", "darkgrey")
// animate the line on hover
.on('mouseover', animateDash)
// turn it off
.on('mouseout', staticDash)
const length = path.node().getTotalLength();
function animateDash() {
path.attr("stroke-dasharray", 8 + " " + 50)
.attr("stroke-dashoffset", length)
.transition()
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0)
.duration(6000)
.on("end", () => setTimeout(animateDash, 1));
}
function staticDash() {
path.attr("stroke-dasharray", 8 + " " + 4)
}
return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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