Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the closest grid coordinate to the mouse position with javascript/jQuery

What I'm trying to do is make a grid of invisible coordinates on the page equally spaced. I then want a <div> to be placed at whatever grid coordinate is closest to the pointer when onclick is triggered. Here's the rough idea:

alt text

I have the tracking of the mouse coordinates and the placing of the <div> worked out fine. What I'm stuck with is how to approach the problem of the grid of coordinates.

First of all, should I have all my coordinates in an array which I then compare my onclick coordinate to?

Or seeing as my grid coordinates follow a rule, could I do something like finding out which coordinate that is a multiple of whatever my spacing is is closest to the onclick coordinate?

And then, where do I start with working out which grid point coordinate is closest? What's the best way of going about it?

Thanks!

like image 460
Acorn Avatar asked Apr 26 '10 10:04

Acorn


2 Answers

In terms of working out which grid point is closest - say, for example, each block is 10x10 pixels - to get the grid index you would just divide them out -

  1. Click at [ 237 ; 112 ]
  2. Blocks of 10x10
  3. Grid index = [ 237/10 ; 112/10 ] = [ 23.7 ; 11.2 ]
  4. Round them to get the "closest"
  5. Block indices are 24;11

If you need to store the data, you could push the grid co-ordinates to an array on click, to reference later.

like image 80
Jeriko Avatar answered Nov 15 '22 04:11

Jeriko


could I do something like finding out which coordinate that is a multiple of whatever my spacing is is closest to the onclick coordinate?

Sure. The whole point of a grid it's it's calculable with simple arithmetic, rather than having to cart around a big array of arbitrary points.

where do I start with working out which grid point coordinate is closest?

It's a simple division with rounding for each axis.

#canvas { position: relative; width: 100px; height: 100px; border: solid red 1px; }
#nearest { position: absolute; width: 10px; height: 10px; background: yellow; }

<div id="canvas"><div id="nearest"></div></div>

var gridspacing= 10;
$('#canvas').mousemove(function(event) {
    var pos= $(this).offset();
    var gridx= Math.round((event.pageX-pos.left)/gridspacing);
    var gridy= Math.round((event.pageY-pos.top)/gridspacing);
    $('#nearest').css('left', (gridx-0.5)*gridspacing+'px').css('top', (gridy-0.5)*gridspacing+'px');
});
like image 37
bobince Avatar answered Nov 15 '22 04:11

bobince