"sticky" 光标沿着 paperjs 中的路径

"sticky" cursor along a path in paperjs

我希望能够沿着 paperjs 中的预定义路径拖动鼠标,并有一个 "sticky" 圆圈标记大致在我的鼠标沿着该路径的位置,中心 路径上的圆圈。

我已经设法得到 pretty close - 下面的代码完全符合我对直线的要求,但它在拐点和圆 "comes off" 的圆心附近不起作用:

var path = new Path();
path.strokeColor = 'black';
path.moveTo([50,50]);
path.lineTo([100,100]);
path.lineTo([150,50]);

var cursorCircle = new Path.Circle({radius: 5,
                                    strokeColor: 'blue',
                                    visible: false});

function onMouseMove(event) {
  cursorCircle.position = event.point;

  var intersections = path.getIntersections(cursorCircle);
  if (intersections.length >= 2) {
    cursorCircle.position = (intersections[0].point + intersections[1].point)/2;
    cursorCircle.visible = true;
  } else if (intersections.length == 1) {
    cursorCircle.position = intersections[0].point;
    cursorCircle.visible = true;
  } else {
    cursorCircle.visible = false;
  }
}

如何让圆圈一直在线(假设光标足够近)?

reference中找到了答案:

var star = new Path.Star({
    center: view.center,
    points: 10,
    radius1: 30,
    radius2: 60,
    strokeColor: 'black'
});

var circle = new Path.Circle({
    center: view.center,
    radius: 3,
    fillColor: 'red'
});

function onMouseMove(event) {
    // Get the nearest point from the mouse position
    // to the star shaped path:
    var nearestPoint = star.getNearestPoint(event.point);

    // Move the red circle to the nearest point:
    circle.position = nearestPoint;
}