Search code examples
react-konvakonva

Konva React - Collision detection for hovered DOM elements


I'm using React with Konva. I am dragging a DOM element onto the canvas and creating a Konva node, just like the lion demo in the docs, except I create a Circle shape from the dropped element.

I want for some validation to happen before the user drops the DOM element onto the canvas, on hover. It should compare an existing Circle shape on the canvas against the hovered DOM element (it will replace the Circle it hovers over) so that it either replaces the existing shape if there is one, or just drops it if there isn't one. I think collision detection might be a good way to approach this?

  1. Do I need to "convert" the DOM element to a Konva node when the user starts dragging, for the validation to happen?
  2. If so, how can I "transfer" the hovered event? Should I create the Konva node from the DOM element's onDragStart and somehow transfer it to the canvas, or how would I do this?

Solution

  • You can use stage.getIntersection(stage.getPonterPosition()) on drop to check if you have a shape under mouse.

    Based on that, you can replace it or create a new one (if there is no shape).

    https://konvajs.org/api/Konva.Stage.html#getIntersection