Zyx Sun
Zyx Sun

Reputation: 439

How to determine the direction of mouse on mousemove event (top-left, top-right, bottom-left and bottom-right)

I have found this question that answers how to determine mouse movement on up, right, down, and left but I need the diagonals rather than the four straight directions.

Here's my code:

var deltaX = window.mxShapeRes - event.offsetX,
    deltaY = window.myShapeRes - event.offsetY;

if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 0) {
    //left
} else if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX < 0) {
    //right
} else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY > 0) {
    //up
} else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY < 0) {
    //down
}

I need to determine if the mouse is going top-left, top-right, bottom-left or bottom-right.

How can I do this with the given code?

Thanks for anyone that can help!

Upvotes: 1

Views: 586

Answers (1)

Tapas
Tapas

Reputation: 1193

You can combine conditions. E.g if mouse is moving top left then deltaX and deltaY would be > 0.

if (deltaY > 0 && deltaX > 0) {
    // top - left
} else if (deltaY > 0 &&  && deltaX < 0) {
    // top - right
} else if (deltaY < 0 &&  && deltaX > 0) {
    // bottom - left
} else if (deltaY < 0 &&  && deltaX < 0) {
    // bottom - right
}

Upvotes: 2

Related Questions