首页 > 解决方案 > 如何通过使用 PaperJS 消除无用点来连接连接的子路径?

问题描述

我有一条路径可以绘制一个原点位于“西”侧的圆,然后通过移除顶部和底部进行拆分。然后我得到三个子路径:

  1. 左上角 1/4 圈
  2. 右半圈
  3. 左下1/4圈

但即使是视觉上的 1 和 3 看起来像一个翻转的 2,1 和 3 实际上是两个子路径。我该如何优化呢?我试过smooth()、flatten() 和simplified() 都不起作用。

这是草图

标签: paperjs

解决方案


根据您的简化案例,您只需构建一个由所有子路径段组成的新路径。为了稍微优化生成的路径,您可以跳过路径 B 的第一段,只保留它的句柄,因为它与路径 A 的最后一段相同。根据您的用例,您还可以使用相同的逻辑跳过路径 B 的最后一段,因为它与路径 A 的第一段相同,并确保生成的路径设置为closed.

这是一个演示可能实现的草图。

const compoundPath = project.importJSON(
    ['CompoundPath', { 'applyMatrix': true, 'children': [['Path', { 'applyMatrix': true, 'segments': [[50, 700], [0, 700], [0, 600], [50, 600]] }], ['Path', { 'applyMatrix': true, 'segments': [[50, 600], [100, 600], [100, 700], [50, 700]] }]] }]
);
compoundPath.strokeColor = 'black';
project.activeLayer.addChild(compoundPath);

const subPaths = [];
compoundPath.children.forEach((child, i) => {
    subPaths.push(
        child
            .clone()
            .translate(0, 150)
            .addTo(project.activeLayer)
    );
});

const assembledPath = assembleSubPaths(subPaths);
assembledPath.strokeColor = 'black';

function assembleSubPaths(subPaths) {
    const path = new Path();
    subPaths.forEach((subPath) => {
        subPath.segments.forEach((segment, segmentIndex) => {
            const isFirstSegment = segmentIndex === 0;
            if (path.segments.length === 0 || !isFirstSegment) {
                path.add(segment);
            } else {
                path.lastSegment.handleOut = segment.handleOut;
            }
        });
        subPath.remove();
    });
    return path;
}


推荐阅读