编程语言
首页 > 编程语言> > javascript – Snap.svg确定沿路径的拖动距离

javascript – 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);
}

解决方法:

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

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

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

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

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

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

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

标签:javascript,html5,svg,raphael,snap-svg
来源: https://codeday.me/bug/20190708/1404876.html