Skip to content Skip to sidebar Skip to footer

Drag Along Path In D3

Using d3 and React I have drawn a path. On this path I have multiple circles which are draggable only along that path. However, my current implementation only (sort of) works when

Solution 1:

Here's a quick modification to this example, which makes the circles draggable:

<!DOCTYPE html><metacharset="utf-8"><style>

path {
  fill: none;
  stroke: #000;
  stroke-width: 1.5px;
}

line {
  fill: none;
  stroke: red;
  stroke-width: 1.5px;
}

circle {
  fill: red;
}

</style><body><scriptsrc="//d3js.org/d3.v3.min.js"></script><script>var points = [[600,276],[586,393],[378,388],[589,148],[346,227],[365,108]];

var width = 960,
    height = 500;

var line = d3.svg.line()
    .interpolate("cardinal");
    
var drag = d3.behavior.drag()
    .on("drag", dragged);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var path = svg.append("path")
    .datum(points)
    .attr("d", line);

var line = svg.append("line");

var circle = svg.append("circle")
  .attr("transform", "translate(" + points[0] + ")")
  .attr("r", 7)
  .call(drag);
    
svg.append("circle")
  .attr("transform", "translate(" + points[5] + ")")
  .attr("r", 7)
  .call(drag);

functiondragged(d) {
  var m = d3.mouse(svg.node()),
    p = closestPoint(path.node(), m);

  d3.select(this)
    .attr("transform", "translate(" + p[0] + "," + p[1] + ")")
}

functionclosestPoint(pathNode, point) {
  var pathLength = pathNode.getTotalLength(),
      precision = 8,
      best,
      bestLength,
      bestDistance = Infinity;

  // linear scan for coarse approximationfor (var scan, scanLength = 0, scanDistance; scanLength <= pathLength; scanLength += precision) {
    if ((scanDistance = distance2(scan = pathNode.getPointAtLength(scanLength))) < bestDistance) {
      best = scan, bestLength = scanLength, bestDistance = scanDistance;
    }
  }

  // binary search for precise estimate
  precision /= 2;
  while (precision > 0.5) {
    var before,
        after,
        beforeLength,
        afterLength,
        beforeDistance,
        afterDistance;
    if ((beforeLength = bestLength - precision) >= 0 && (beforeDistance = distance2(before = pathNode.getPointAtLength(beforeLength))) < bestDistance) {
      best = before, bestLength = beforeLength, bestDistance = beforeDistance;
    } elseif ((afterLength = bestLength + precision) <= pathLength && (afterDistance = distance2(after = pathNode.getPointAtLength(afterLength))) < bestDistance) {
      best = after, bestLength = afterLength, bestDistance = afterDistance;
    } else {
      precision /= 2;
    }
  }

  best = [best.x, best.y];
  best.distance = Math.sqrt(bestDistance);
  return best;

  functiondistance2(p) {
    var dx = p.x - point[0],
        dy = p.y - point[1];
    return dx * dx + dy * dy;
  }
}

</script>

Post a Comment for "Drag Along Path In D3"