Makaku00
Makaku00

Reputation: 121

Determine all SVG elements on a certain coordinate (mouseclick)

What i need is a clickhandler to be able to work on multiple layered objects in an SVG, paths or lines for example. What would be the best approach to determine all the elements that pass through a certain coordinate.

Upvotes: 1

Views: 98

Answers (2)

altocumulus
altocumulus

Reputation: 21578

Probably the simplest solution is to use document.elementsFromPoint():

The elementsFromPoint() property of the DocumentOrShadowRoot interface returns an array of all elements at the specified coordinates (relative to the viewport).

The browser compatibility is good and it will give you all the elements with a single call.

Upvotes: 1

Robert Longson
Robert Longson

Reputation: 124129

  1. Call document.elementFromPoint - that will tell you the frontmost element under the mouse
  2. If any element is found in step 1, set that element to be pointer-events: none and return to step 1.
  3. If not quit, you will have found all the elements in the above loop. Don't forget to delete the pointer-events property you've set on all the elements you found or you won't find them next time.

Upvotes: 2

Related Questions