Created
June 9, 2022 14:09
-
-
Save felixhaeberle/4e6966f00cc5af17ddc1f169dc78b4a9 to your computer and use it in GitHub Desktop.
JavaScript: Calculate polar angle in degree (φ) from a cursor position and a midpoint center
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Read this article for full understanding: https://de.serlo.org/mathe/45643/polarkoordinaten | |
// We need two coordinates for this calculation: the cursor coordinate and midpoint coordinate. | |
// How the sricpt works: | |
// 1. It calculates the distance between the points | |
// 2. It calculates the polar angle (in degree) | |
// 3. If the coordinates are overlapping, it calculates the edge cases also. | |
// It returns the polar angle as a number | |
const getPolarAngle = (cursor: {x: number; y: number}, midpoint: {x: number; y: number}): number => { | |
/* Degree */ | |
let polarX: number; | |
let polarY: number; | |
let polarDegree: number = 0; | |
// First case | |
if(midpoint && cursor) { | |
if (midpoint.x < cursor.x && midpoint.y < cursor.y) { | |
polarX = cursor.x - midpoint.x; | |
polarY = cursor.y - midpoint.y; | |
console.log('first', polarX, polarY); | |
polarDegree = ~~(Math.atan(polarY/polarX) * (180/Math.PI) + 180) | |
} | |
// Second Case | |
if (midpoint.x > cursor.x && midpoint.y < cursor.y) { | |
polarX = midpoint.x - cursor.x; | |
polarY = midpoint.y - cursor.y; | |
console.log('second', polarX, polarY); | |
polarDegree = ~~(Math.atan(polarY/polarX) * (180/Math.PI)) | |
} | |
// Third Case | |
if(midpoint.x < cursor.x && midpoint.y > cursor.y) { | |
polarX = cursor.x - midpoint.x; | |
polarY = cursor.y - midpoint.y; | |
console.log('third', polarX, polarY); | |
polarDegree = ~~(Math.atan(polarY/polarX) * (180/Math.PI) + 180) | |
} | |
// Forth case | |
if(midpoint.x > cursor.x && midpoint.y > cursor.y) { | |
polarX = midpoint.x - cursor.x; | |
polarY = midpoint.y - cursor.y; | |
console.log('forth', polarX, polarY); | |
polarDegree = ~~(Math.atan(polarY/polarX) * (180/Math.PI)) | |
} | |
/* Overlapping values */ | |
if (midpoint.x === cursor.x && midpoint.y > cursor.y) { | |
return -270 // Bottom | |
} else if (midpoint.x === cursor.x && midpoint.y < cursor.y) { | |
return -90; // Top | |
} else if (midpoint.x === cursor.x && midpoint.y === cursor.y) { | |
return 180; // Middle | |
} else if (midpoint.y === cursor.y && midpoint.x < cursor.x) { | |
return -180; // Left | |
} else if (midpoint.y === cursor.y && midpoint.x > cursor.x) { | |
return 0; // Right | |
} | |
} | |
return polarDegree; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment