ball on path

When you click, a ball moves along a simple path.

by Igor Cuckovic

JavaScript

var data = [
  {x: 0, y:0},
  {x: 62, y:66},
  {x: 259, y:134},
  {x: 339, y:10},
  {x: 400, y:30}
  ]
 
var line = d3.svg.line()
  .x(function(d) {
    return d.x;
  })
  .y(function(d) {
    return d.y;
  });


  
var svg = d3.select("body").append("svg").attr({"width": 640, "height": 480});
  
var group = svg.append("g")
  .attr({
  transform: "translate(" + [60, 150] + ")"
  })
  
var path = group.selectAll("path")
  .data([data])
  .enter()
  .append("path")
  .attr({
  "d": line,
  fill: "none",
  stroke: "#000"
  })


//now create a ball and animate it to move along a line.

var len = path.node().getTotalLength();
var offset = len * -0.0599999999999999;

path.attr({
  "stroke-dasharray": len + " " + len,
  "stroke-dashoffset": offset

})


var ball = group.append("circle")
.attr({
  "r": 10,
  "transform": function () {
    var p = path.node().getPointAtLength(len - offset);
    return "translate(" + [p.x, p.y] + ")";
  }
})


svg.on("click", function () {
	path.transition()
    .duration(2000)
    .ease("bounce")
    .attrTween("stroke-dashoffset", function (d,i) {
      return function (t) {
        return len * (1-t);
      }
    })
    
    ball.transition()
    .duration(2000)
    .ease("bounce")
    .attrTween("transform", function (d,i) {
      return function (t) {
        var p = path.node().getPointAtLength(len * t);
        return "translate(" + [p.x, p.y] + ")";
          console.log(t);
      }
    })
})