jonobr1 / two.js

A renderer agnostic two-dimensional drawing api for the web.
https://two.js.org
MIT License
8.27k stars 454 forks source link

[Question] Select functionality for different kind of shapes #730

Open rael346 opened 1 month ago

rael346 commented 1 month ago

Hi,

I'm currently playing around with two.js to build a select functionality for custom shapes (grouped shapes like circles + points, circle with only the outline, etc). The functionality will allow the user to hover on a shape (the pointer will change to indicate this), and on pointer down the user can move the shape around the canvas area. Since I am doing this on the canvas renderer instead of the SVG one, I will have to roll my own logic for this.

My idea is to just maintain a list of shapes and for each type of shapes have their own checks for when a point is in a shape. I was wondering if there is another approach to this?

Environment (please select one):

jonobr1 commented 1 month ago

There are other questions in the issues section that cover various means of hit testing for non-SVG renderers. I hope to tackle this officially soon.

In the meantime the simplest way is to iterate through all the objects in a group or scene that you'd like to hit test against, get their bounding rectangle and do a simple if statement. This is a rough estimate (as in it's not exactly over a given paths form). But, it gets you close is and also on the more performant side.

This library also plays well with Physics engines like: https://brm.io/matter-js/ to do more complex hit testing.

Hope this helps!