You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Paper.js中获取两个独立CompoundPath的最近Location配对

解决CompoundPath间最近Location配对问题

我有两个互不相交的CompoundPath对象,想要获取每个路径上与另一路径最近Location对应的Location。已知Path.getNearestLocation()方法仅接受Point作为参数,需要实现类似path1.getClosestLocations(path2)的功能。

实现思路

CompoundPath由多个子Path组成,需遍历所有子Path组合,通过采样+精确校验的方式找到全局最近的Location对:

  1. 拆分CompoundPath为子Path列表
const pathsFromComp1 = compoundPath1.getPaths();
const pathsFromComp2 = compoundPath2.getPaths();
  1. 全局遍历采样,筛选初步最近点
    在子Path上均匀采样Location,用getNearestLocation()获取对应另一路径的最近点,记录距离最小的组合:
let minDist = Infinity;
let result = { locOnComp1: null, locOnComp2: null };

pathsFromComp1.forEach(pathA => {
  pathsFromComp2.forEach(pathB => {
    // 采样密度可根据路径复杂度调整
    const sampleSteps = 100;
    for (let i = 0; i <= sampleSteps; i++) {
      const t = i / sampleSteps;
      const locA = pathA.getLocationAt(t);
      const locB = pathB.getNearestLocation(locA.point);
      const currentDist = locA.point.getDistance(locB.point);

      if (currentDist < minDist) {
        minDist = currentDist;
        result = { locOnComp1: locA, locOnComp2: locB };
      }
    }
  });
});
  1. 高精度二次校验(可选)
    如果需要更精确的结果,在初步找到的点附近进行细分采样:
if (result.locOnComp1) {
  const targetPathA = pathsFromComp1.find(p => p.containsLocation(result.locOnComp1));
  const targetPathB = pathsFromComp2.find(p => p.containsLocation(result.locOnComp2));
  const initialT = result.locOnComp1.time;
  const precisionRange = 0.05; // 校验范围
  const precisionSteps = 50;

  for (let i = -precisionSteps; i <= precisionSteps; i++) {
    const adjustedT = Math.max(0, Math.min(1, initialT + i * precisionRange / precisionSteps));
    const refinedLocA = targetPathA.getLocationAt(adjustedT);
    const refinedLocB = targetPathB.getNearestLocation(refinedLocA.point);
    const dist = refinedLocA.point.getDistance(refinedLocB.point);

    if (dist < minDist) {
      minDist = dist;
      result = { locOnComp1: refinedLocA, locOnComp2: refinedLocB };
    }
  }
}

最终结果

result.locOnComp1 是第一个CompoundPath上离第二个路径最近的Location,result.locOnComp2 是第二个CompoundPath上对应的最近Location。

内容的提问来源于stack exchange,提问作者viggity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 03:35:25