我们如何获得 Paper.js 中路径的基础几何形状?

How do we get underlying geometry of a Path in Paper.js?

我们可以通过多种方式绘制矩形,其中一种是先定义一个 Rectangle 然后用 Path.Rectangle 绘制它:

var rect = new Rectangle({
    from: [80, 50],
    to: [100, 200]
})

var rpath = new Path.Rectangle(rect)
rpath.strokeColor = 'red'

在这一点之后,如果我们松散rect(如果我们不保留指针或者我们export/import项目),我们就无法知道rpath是一个Rectangle 与否。

我们如何确定 PathCircle 还是 Rectangle 还是 Polygon 还是 Polyline

Path.RectanglePath.Circle 等...只是 factory functions that return a Path看起来 就像一个矩形。他们不是 subclasses/types.

所以不,没有直接的方法来推断类型。

作为解决方法,您可以在 item.data 中存储一个 type 道具,它在 serialisation/reimporting.

中继续存在
var rect = new Rectangle({
    from: [80, 50],
    to: [100, 200]
})

var rpath = new Path.Rectangle(rect)
rpath.strokeColor = 'red'
rpath.data = { type: 'rectangle' }

var serialized = rpath.exportJSON()
var reimported = paper.project.importJSON(serialized)

console.log(reimported.data.type)

这是 Sketch

您可以尝试其他解决方案:

  • Path 子类化为您自己的 Rectangle 类型。通过 paper.Path.extend().
  • 官方不支持子类化,但仍然可行
  • 添加一个方法 Path.isRectangle(),它在运行时检查线段并通过数学方式确定它是否为矩形。