Skip to content

Instantly share code, notes, and snippets.

@basilesimon
Forked from methodofaction/index.html
Last active January 18, 2017 18:14
Show Gist options
  • Save basilesimon/f164aec5758d16d51d248e41af5428e4 to your computer and use it in GitHub Desktop.
Save basilesimon/f164aec5758d16d51d248e41af5428e4 to your computer and use it in GitHub Desktop.
Animate path in D3
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<style type="text/css">
#line{
width: 100%;
margin: 20px 0;
height: 300px;
}
.old {
stroke: lightgrey;
stroke-dasharray: 5;
stroke-dashoffset: 5;
}
​</style>
</head>
<body>
<div id="line"></div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.4.1/d3.min.js"></script>
<script type="text/javascript">
var w = window.innerWidth;
var h = 100;
var svg = d3.select("#line")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("id", "visualization");
var x = d3.scaleLinear().domain([0, 10]).range([0, w]);
var y = d3.scaleLinear().domain([0, 10]).range([10, h - 10]);
var line = d3.line()
.x(function(d,i) {return x(i);})
.y(function(d) {return y(d);})
.curve(d3.curveNatural)
// data is created inside the function so it is always unique
let repeat = () => {
var data = d3.range(11).map(function(){return Math.random()*10})
// Uncomment following line to clear the previously drawn line
//svg.selectAll("path").remove();
// Set a light grey class on old paths
svg.selectAll("path").attr("class", "old");
var path = svg.append("path")
.attr("d", line(data))
.attr("stroke", "darkgrey")
.attr("stroke-width", "2")
.attr("fill", "none");
var totalLength = path.node().getTotalLength();
path
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(4000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0)
.on("end", repeat);
};
repeat();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment