Search code examples
paperjs

How to create a hole on a Path in Paper.js?


I want to get a result like this while the white circle is being actually a punch:

enter image description here

However, I'm getting the following result when I follow the boolean operation example:

// this works okay 
var via = outer.exclude(hole)
project.activeLayer.addChild(via)

// this works weird 
var drilledY = y.exclude(hole)
project.activeLayer.addChild(drilledY)

enter image description here

Here the only problem seems to be creating the hole inside the Path. How can I create a hole in the path?


Solution

  • I don't think you can get the result you want using Path.Line.

    Punching through implies that you want to remove some internal area, which an open Path such as Path.Line lacks.

    So what you can do is the following:

    • Replace those thick Lines with Path.Rectangles.
    • unite the 2 rectangles, to get your cross, so you have one Path to operate on.
    • Use subtract instead of exclude to "punch through".

    Here's an example:

    var x = new paper.Path.Rectangle({
        from: [100, 100],
        to: [120, 200],
        fillColor: 'red',
        strokeWidth: 1
    });
    
    var y = x.clone().rotate(90).set({ fillColor: 'blue' })
    
    // Unite x/y to get a single path.
    var cross = y.unite(x)
    
    // Remove x,y we no longer need them, we got the cross.
    x.remove()
    y.remove()
    
    var hole = new paper.Path.Circle({
        center:[110, 150],
        radius: 6,
        strokeColor: 'red',
        fillColor: 'red'
    })
    
    // Subtract (instead of exclude), to "punch through".
    var drilled = cross.subtract(hole)
    
    // Remove hole/cross, we no longer need them.
    hole.remove()
    cross.remove()
    
    console.log(drilled)
    

    and here's a Sketch.

    If you don't want to unite your shapes, you can still loop through them and subtract the hole from them, just remember to use closed Paths.