# Find the closest grid vertex to the mouse position

**URL:** https://discourse.threejs.org/t/find-the-closest-grid-vertex-to-the-mouse-position/59838
**Category:** Questions
**Tags:** math
**Created:** [January 1, 2024, 10:16pm UTC](https://discourse.threejs.org/t/find-the-closest-grid-vertex-to-the-mouse-position/59838 "2024-01-01T22:16:22Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![birdblue0311](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.threejs.org/birdblue0311/32/41527_2.png) [@birdblue0311](https://discourse.threejs.org/u/birdblue0311)
#### Post date: [January 1, 2024, 10:16pm UTC](https://discourse.threejs.org/t/find-the-closest-grid-vertex-to-the-mouse-position/59838/1 "2024-01-01T22:16:22Z")

</div>

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](https://jsfiddle.net/kirill321592/1yx5pro6/22/)

Any ideas would be highly appreciated.

---

<div class="post-metadata">

### Author: ![anidivr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.threejs.org/anidivr/32/32924_2.png) [@anidivr](https://discourse.threejs.org/u/anidivr)
#### Post date: [January 2, 2024, 3:05am UTC](https://discourse.threejs.org/t/find-the-closest-grid-vertex-to-the-mouse-position/59838/2 "2024-01-02T03:05:50Z")

</div>

```js
      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;

```
