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

时间:2014-05-22 16:22:11

标签: javascript html5 svg raphael snap.svg

作为引用here并更新以用于Snap.svg here,我想更好地理解提供的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);
}

1 个答案:

答案 0 :(得分:1)

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

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

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

if语句然后确定要拖入的方向。它通过将searchDl值添加到路径位置(即沿路径的长度),并减去相同的值并查看哪个是更接近鼠标位置。

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

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

通过将searchDir更改为更大的值,您可以以更大的增量移动,并且可以更高的精度计算(如果我已正确理解代码)。

相关问题