This is an example of animating an object to move along a defined path. The path must be an existing SVG path object, but can be hidden if you want.
Last active
December 22, 2015 09:59
-
-
Save JMStewart/6455921 to your computer and use it in GitHub Desktop.
Animate along a path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
</head> | |
<body> | |
<script> | |
var svg = d3.select("body").append("svg") | |
.attr("width", 500) | |
.attr("height", 500); | |
var line = d3.svg.diagonal(); | |
var lineData = {source:{x:25, y:25}, | |
target:{x:400, y:400}}; | |
var path = svg.append("path") | |
.attr("d", line(lineData)) | |
.style("stroke", "black") | |
.style("fill", "none"); | |
svg.append("circle") | |
.attr("cx", 25) //Starting x | |
.attr("cy", 25) //Starting y | |
.attr("r", 25) | |
.transition() | |
.delay(250) | |
.duration(1000) | |
.ease("linear") | |
.tween("pathTween", function(){return pathTween(path)}) | |
// .tween("pathTween", pathTween); //Custom tween to set the cx and cy attributes | |
function pathTween(path){ | |
var length = path.node().getTotalLength(); // Get the length of the path | |
var r = d3.interpolate(0, length); //Set up interpolation from 0 to the path length | |
return function(t){ | |
var point = path.node().getPointAtLength(r(t)); // Get the next point along the path | |
d3.select(this) // Select the circle | |
.attr("cx", point.x) // Set the cx | |
.attr("cy", point.y) // Set the cy | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment