Snap.svg 确定沿路径的拖动距离

Ina*_*tor 5 html javascript svg raphael snap.svg

正如此处引用并在此处更新以与 Snap.svg 一起使用,我想更好地了解提供的 gradSearch 函数实际上是如何工作的(这有点超出我的理解),以及这种方法是否有任何好的替代方案?

gradSearch = function (l0, pt) {
    l0 = l0 + totLen;
    var l1 = l0,
        dist0 = dist(path.getPointAtLength(l0 % totLen), pt),
        dist1,
        searchDir;

    if (dist(path.getPointAtLength((l0 - searchDl) % totLen), pt) > 
       dist(path.getPointAtLength((l0 + searchDl) % totLen), pt)) {
        searchDir = searchDl;
    } else {
        searchDir = -searchDl;
    }

    l1 += searchDir;
    dist1 = dist(path.getPointAtLength(l1 % totLen), pt);
    while (dist1 < dist0) {
        dist0 = dist1;
        l1 += searchDir;
        dist1 = dist(path.getPointAtLength(l1 % totLen), pt);
    }
    l1 -= searchDir;
    return (l1 % totLen);
}
Run Code Online (Sandbox Code Playgroud)

hya*_*ion 3

我花了一段时间来理解代码,但这就是我理解它工作的方式(试图简化解释):

首先将可拖动对象在路径上的位置记录为l0(注意这是L0,第一次看代码时很容易与数字 10 混淆)。

从新点(鼠标拖动到的位置)到路径上位置的距离记录为dist0

然后,该if语句确定向哪个方向拖动。它通过searchDl向路径位置(即沿路径的长度)添加值,然后减去相同的值并查看哪个更接近鼠标位置来实现此目的。

一旦它知道要向哪个方向移动,它就会使用while循环不断地按大小添加/减去位置,searchDl直到路径上的点与鼠标位置之间的距离尽可能小。

然后它返回路径上的新位置。

通过更改searchDir为更大的值,您可以以更大的增量移动,并且可以以牺牲精度为代价更快地计算(如果我正确理解了代码)。