Fred
Fred

Reputation: 35

Mouse Proximity to object Javascript

I'm struggling with this for a while now. I'm drawing a grid on the canvas. I add a mousemove eventHandler and track the mouseX and mouseY positions. I would like to be able to calculate the distance from the mouse position to the item in the grid. I can't seem to get this right, I've tried a few different solutions, like adding a loop in the mousemove handler and using requestAnimationFrame, but both solutions are very slow.

Here's my code below:

    function setupCanvas(){
        canvas  = document.getElementById('canvas');
        ctx     = canvas.getContext('2d');
        width   = canvas.width  = window.innerWidth;
        height  = canvas.height = window.innerHeight;
        blockWidth = width/2 - 150;
        blockHeight = height/2 - 100;
        gridArray   = [];
        gridWidthArray = [];

        ctx.fillRect(0,0,width,height);

        //drawGrid();
        drawInitGrid();

        canvas.addEventListener('mousemove',onMouseMoveHandler);
    }

   function drawInitGrid(){

        for(x = 0; x<16; x++){
            for(y = 0; y<11; y++){
                var gridBlock = new GridBlock((blockWidth) + x*20, (blockHeight) + y*20, blockWidth, blockHeight);
                gridBlock.render(ctx);
                gridArray.push(gridBlock);

                //gridWidthArray.push(gridBlock.xPos)
            }
        }
    }

function onMouseMoveHandler(e){
        if(containerBounds(e)){
            mouseX = e.offsetX;
            mouseY = e.offsetY;
            console.log(mouseX, mouseY);
            //console.log(gridWidthArray);

            for(var grid in gridArray){
                //console.log(gridArray[grid].xPos)
            }
        }
    }

I've also tried adding a mouseevent in the GridBlock object, but that also doesn't seem to work.

Upvotes: 1

Views: 939

Answers (1)

markE
markE

Reputation: 105035

You can calculate the distance between any 2 points like this:

var dx=point2.x-point1.x;
var dy=point2.y-point1.y;
var distance=Math.sqrt(dx*dx+dy*dy);

Also in your fiddle your mouse position calculation should account for the offset position of the canvas within the window:

var BB=canvas.getBoundingClientRect();
var offsetX=BB.left;
var offsetY=BB.top;

function onMouseMoveHandler(e){
     var mouseX=parseInt(e.clientX-offsetX);
     var mouseY=parseInt(e.clientY-offsetY);
}

[ Finding nearest point in grid ]

Assume you have a mouse position [mx,my] and assume you have a grid with its top-left at [0,0] and with its cell size at cellWidth X cellHeight.

Then you can calculate the grid cell closest to the mouse like this:

var cellX=parseInt((mx+cellWidth/2)/cellWidth)*cellWidth;
var cellY=parseInt((my+cellHeight/2)/cellHeight)*cellHeight;

Of course, if the grid's top-left is not at [0,0], you will have to adjust for the gridss offset.

Upvotes: 1

Related Questions