This example demonstrates how to use the getTotalLength and getPointAtLength methods on SVG path elements to interpolate a point along a Catmull–Rom spline.
A related technique is stroke dash interpolation.
forked from mbostock's block: Point-Along-Path Interpolation
xxxxxxxxxx
<meta charset="utf-8">
<body>
<style>
path {
fill: none;
stroke: #000;
stroke-width: 3px;
}
circle {
fill: steelblue;
stroke: #fff;
stroke-width: 3px;
}
</style>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var points = [
[200, 200],
[500, 200],
[500, 400],
[200, 400],
];
var points2 = [
[100, 200],
[400, 200],
[400, 400],
[100, 400],
];
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var dataset = [];
var path = svg.append("path")
.data([points])
.attr("d", d3.svg.line()
.tension(0) // Catmull–Rom
.interpolate("cardinal-closed"));
var path2 = svg.append("path")
.data([points2])
.attr("d", d3.svg.line()
.tension(0) // Catmull–Rom
.interpolate("cardinal-closed"));
// OPTIONAL
svg.selectAll(".point")
.data(points)
.enter().append("circle")
.attr("r", 4)
.attr("transform", function(d) { return "translate(" + d + ")"; });
// OPTIONAL
/*
var circle = svg.append("circle")
.attr("r", 13)
.attr("transform", "translate(" + points[0] + ")");
*/
d3.select("svg").on("click", function()
{
// get the mouse position coordinates
var coordinates = [0, 0];
coordinates = d3.mouse(this);
var x = coordinates[0];
var y = coordinates[1];
dataset.push(10);
var circles = svg.selectAll("circle") //Select all circles
.data(dataset);
circles.enter()
.append("circle")
.attr({cx:x, cy:y, fill:"red"})
.attr("r", function(d){return d})
.attr("transform", "translate(" + points[0] + ")")
transition();
function transition() {
circles.transition()
.duration(10000)
.attrTween("transform", translateAlong(path.node()))
.each("end", transition);
}
});
// Returns an attrTween for translating along the specified path element.
function translateAlong(path) {
var l = path.getTotalLength();
return function(d, i, a) {
return function(t) {
var p = path.getPointAtLength(t * l);
return "translate(" + p.x + "," + p.y + ")";
};
};
}
</script>
https://d3js.org/d3.v3.min.js