Skip to content

Instantly share code, notes, and snippets.

@methodofaction
Created November 13, 2012 01:37
Show Gist options
  • Save methodofaction/4063326 to your computer and use it in GitHub Desktop.
Save methodofaction/4063326 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: 700px;
margin: 20px 0;
height: 300px;
background: #eee;
}
button {
margin: 20px 0 0 20px;
}
​</style>
</head>
<body>
<div id="line"></div>​
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.5.0"></script>
<script type="text/javascript">
var w = 700;
var h = 300;
var svg = d3.select("#line")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("id", "visualization")
.attr("xmlns", "http://www.w3.org/2000/svg");
var data = d3.range(11).map(function(){return Math.random()*10})
var x = d3.scale.linear().domain([0, 10]).range([0, 700]);
var y = d3.scale.linear().domain([0, 10]).range([10, 290]);
var line = d3.svg.line()
.interpolate("cardinal")
.x(function(d,i) {return x(i);})
.y(function(d) {return y(d);})
var path = svg.append("path")
.attr("d", line(data))
.attr("stroke", "steelblue")
.attr("stroke-width", "2")
.attr("fill", "none");
var totalLength = path.node().getTotalLength();
path
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(2000)
.ease("linear")
.attr("stroke-dashoffset", 0);
svg.on("click", function(){
path
.transition()
.duration(2000)
.ease("linear")
.attr("stroke-dashoffset", totalLength);
})
</script>
</body>
</html>
@aarthi0808
Copy link

Looking great. Thanks! I searched for this (animated path). But have you check,its not working properly in Firefox.Animation starts with full path and erases it and draw it again ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment