Search code examples
paperjs

Detecting Overlapping objects in Paper JS


One rectangle and a couple of circles are on canvas. Scattered. The circles which are on top of rectangle needs to be of different color.

Circle must be completely inside the rectangle.

How can I detect this in Paper JS.


Solution

  • The method item.isInside(rectangle) seems to perfectly match your need.

    Here is a sketch demonstrating the solution.

    // create 3 circles scattered on the canvas.
    var circles = [
        new Path.Circle({
            center: view.center - 100,
            radius: 50,
            fillColor: 'orange'
        }),
        new Path.Circle({
            center: view.center,
            radius: 50,
            fillColor: 'orange'
        }),
        new Path.Circle({
            center: view.center + 150,
            radius: 50,
            fillColor: 'orange'
        })
    ];
    
    // Create a rectangle.
    var rectangle = new Path.Rectangle({
        from: view.center - 80,
        to: view.center + 80,
        strokeColor: 'black'
    });
    
    // Scale things up so that we can see better.
    project.activeLayer.fitBounds(view.bounds.scale(0.8));
    
    // For each circle...
    circles.forEach(circle => {
        // ...if circle is contained in rectangle bounds...
        if (circle.isInside(rectangle.bounds)) {
            // ...change circle color.
            circle.fillColor = 'blue';
        }
    });