Skip to content

Instantly share code, notes, and snippets.

@jdpigeon
Last active June 4, 2020 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdpigeon/f5dfb458fba3b86e9a0bd340404032a8 to your computer and use it in GitHub Desktop.
Save jdpigeon/f5dfb458fba3b86e9a0bd340404032a8 to your computer and use it in GitHub Desktop.
Animated line from random dataset
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>d3.js | SVG paths</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
const w = 960,
h = 500;
// Just generate a randomly quivery line path
const dataset = [];
let lastPoint = { x: 10, y: 20 };
for (let i = 0; i < 60; i++) {
const x = lastPoint.x + Math.random() * 1;
const y = lastPoint.y + Math.random() * 2;
lastPoint = { x, y };
dataset.push(lastPoint);
}
const xScale = d3
.scaleLinear()
// domain = range of our data values
.domain([0, 100])
// range = range of the pixel values we want data mapped to
.range([0, w]);
const yScale = d3.scaleLinear().domain([0, 100]).range([h, 0]);
const lineFunction = d3
.line()
.x((d) => xScale(d.x))
.y((d) => yScale(d.y));
svgViewport = d3.select('body').append('svg').attr('width', w).attr('height', h);
svgViewport
.append('path')
.datum(dataset)
.attr('d', lineFunction)
.attr('stroke', 'black')
.attr('stroke-width', 3)
.attr('fill', 'none')
// Animation works by hiding the line with dash offset and lowering it to 0
.attr('stroke-dasharray', w + ' ' + w)
.attr('stroke-dashoffset', w)
.transition()
.attr('stroke-dashoffset', 0)
.duration(3000)
// There's a bunch of different easing functions here: https://github.com/d3/d3-ease
.ease(d3.easeSin);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment