Find the closest grid vertex to the mouse position

I’m trying to figure out how to find the closest grid vertex to the mouse cursor position. Let’s say I have a threejs gridHelper on which I want to implement a drawing of a polyline with “snapping” functionality . When hovering over the grid with the mouse cursor, I would like to know which is the closest grid cell vertex that I would need to “snap” to in order to continue drawing the polyline with my mouse.

I looked for different ways to achieve this, but without any progress. I found an example showing how to highlight edges of a mesh, but I’m unsure if some of the code would be helpful for what I need: Edit fiddle - JSFiddle - Code Playground

Any ideas would be highly appreciated.

      if (gridSize > 0) {
        // Assuming position is the position of the object being dragged
        position.x = Math.round(position.x / gridSize) * gridSize;
        position.y = Math.round(position.y / gridSize) * gridSize;
        position.z = Math.round(position.z / gridSize) * gridSize;
      return position;