Search code examples
paperjs

Finding object being clicked in a set of overlapped objects


There is a circle at the intersection of two lines. How can I figure out if the mouse is clicked on top of circle, line 1, line 2, or somewhere else?

I have used if-then-else ladder to test object.hitTest within view.onClick function. I am testing for lines first and then circle.

sketch link

When I click at circle anywhere within overlapping area with lines, then all the three hitTest return HitResult. What can I do so that only circle hitTest passes through when I click anywhere on the circle.


Solution

  • I am not sure if this is what you are trying to do, but you can hit test all items at once by calling project.hitTest().
    Only the topmost item will match.

    Here is a sketch demonstrating the solution.

    var myLine1 = new Path.Line({
        from: [50, 50],
        to: [150, 50],
        strokeColor: 'black',
        strokeWidth: 10,
        name: 'myLine1'
    });
    
    var myLine2 = new Path.Line({
        from: [150, 50],
        to: [150, 100],
        strokeColor: 'black',
        strokeWidth: 10,
        name: 'myLine2'
    });
    
    var myCircle = new Path.Circle({
        center: [150, 50],
        radius: 10,
        strokeColor: 'red',
        fillColor: 'red',
        name: 'myCircle'
    });
    
    view.onClick = function(event) {
        var hitTest = project.hitTest(event.point);
        if (hitTest) {
            alert('Clicked on item: ' + hitTest.item.name);
        } else {
            alert('Clicked elsewhere');
        }
    };