p5.js icon indicating copy to clipboard operation
p5.js copied to clipboard

Hit detection on 2D Shapes

Open Matoseb opened this issue 1 year ago • 2 comments

Increasing access

Useful for mouse interaction (mousehover, mouseclick, etc.) on 2DShapes (rect, ellipse, beginShape, ...)

Most appropriate sub-area of p5.js?

  • [ ] Accessibility
  • [ ] Color
  • [ ] Core/Environment/Rendering
  • [ ] Data
  • [ ] DOM
  • [X] Events
  • [ ] Image
  • [ ] IO
  • [X] Math
  • [ ] Typography
  • [X] Utilities
  • [ ] WebGL
  • [ ] Build process
  • [ ] Unit testing
  • [ ] Internationalization
  • [ ] Friendly errors
  • [ ] Other (specify if possible)

Feature request details

Using CanvasRenderingContext2D: isPointInPath() and isPointInStroke() this could be doable.

Here are two sketches showing how it would work, the shape is drawn two times, the first one for hit detection (drawn as transparent), and the second for styling (fill, stroke, ...)

Example


const hit = hitTest(mouseX, mouseY, () => {
  rect(0, 0, 500, 500)
})

fill('black')
stroke('white')
cursor(ARROW)

if (hit.hasHit) cursor(HAND)

if (hit.inStroke) stroke('red')
else if (hit.inFill) fill('red')

hit.draw()

Matoseb avatar Jun 01 '24 14:06 Matoseb

Welcome! 👋 Thanks for opening your first issue here! And to ensure the community is able to respond to your issue, please make sure to fill out the inputs in the issue forms. Thank you!

welcome[bot] avatar Jun 01 '24 14:06 welcome[bot]

A couple of initial discussion points to kick things off...

A feature like this does seem like it would make building certain interactive sketches more accessible. Specifically, detecting mouseover on rectangles with rounded corners or custom shapes created with beginShape and endShape seems hard right now, and this would make it more manageable for beginners.

One concern I have is the interface shown in the example you provided

const hit = hitTest(mouseX, mouseY, () => { rect(0, 0, 500, 500) })

Passing an arrow function as a parameter might confuse JavaScript beginners. Is there a way to better abstract away the details of hitTest's implementation?

Also note that there are libraries like p5.collide2D--do you still think collisions with non-trivial shapes is common enough to warrant native support for this feature?

ericnlchen avatar Sep 06 '24 22:09 ericnlchen

Passing function as parameters does exist in p5, for instance: button.mousePressed(callback). Also this helper function clearly targets intermediate users

Haven't used p5 collide, but I feel my function is less verbose to use, and works with stroke hit collision too.

Matoseb avatar Mar 05 '25 11:03 Matoseb