ceremcem
ceremcem

Reputation: 4350

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

We can draw a rectangle in many ways and one of them is first defining a Rectangle and then draw it with Path.Rectangle:

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

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

After this point, if we loose rect (if we don't keep the pointer or we export/import the project), we can not know rpath is a Rectangle or not.

How can we decide if a Path is Circle or Rectangle or Polygon or Polyline?

Upvotes: 2

Views: 145

Answers (1)

nicholaswmin
nicholaswmin

Reputation: 22939

Path.Rectangle, Path.Circle etc... are simply factory functions that return a Path, which simply looks like a rectangle. They are not subclasses/types.

So no, there's no straightforward way to infer the type.

As a workaround, you can store a type prop in item.data, which survives 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)

And here's the Sketch.

There are other solutions you can try:

  • Subclass Path to your own Rectangle type. Subclassing is not officially supported but still doable, through paper.Path.extend().
  • Add a method Path.isRectangle() which inspects the segments and mathematically determines if it's a rectangle or not, at runtime.

Upvotes: 2

Related Questions