引用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 - Snap.svg 确定沿路径的拖动距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23812322/