Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding reflection of a point relative to another point in JavaScript
Point reflection, also known as point symmetry, is a geometric transformation where a point P is reflected across a midpoint Q to create a new point P' that is equidistant from Q but in the opposite direction.
The Formula
To find the reflection of point P across point Q, we use the formula:
- P'x = 2 × Qx - Px
- P'y = 2 × Qy - Py
Implementation
Here's how to implement point reflection in JavaScript:
const p = {
x: 6, y: -4
};
const q = {
x: 11, y: 5
};
const findReflection = (p = {}, q = {}) => {
const res = {};
const Xdistance = p['x'] - q['x'];
res['x'] = q['x'] - Xdistance;
let Ydistance = p['y'] - q['y'];
res['y'] = q['y'] - Ydistance;
return res;
};
console.log(findReflection(p, q));
{ x: 16, y: 14 }
Alternative Approach Using Direct Formula
We can simplify the function using the direct formula:
const findReflectionDirect = (p, q) => {
return {
x: 2 * q.x - p.x,
y: 2 * q.y - p.y
};
};
// Test with same points
const point = { x: 6, y: -4 };
const center = { x: 11, y: 5 };
console.log(findReflectionDirect(point, center));
{ x: 16, y: 14 }
How It Works
The reflection works by:
- Finding the distance vector from Q to P
- Extending the same distance from Q in the opposite direction
- The formula P' = 2Q - P achieves this mathematically
Multiple Points Example
const reflectPoints = (points, center) => {
return points.map(point => ({
x: 2 * center.x - point.x,
y: 2 * center.y - point.y
}));
};
const points = [
{ x: 1, y: 2 },
{ x: 5, y: 7 },
{ x: -2, y: 3 }
];
const center = { x: 0, y: 0 };
console.log(reflectPoints(points, center));
[
{ x: -1, y: -2 },
{ x: -5, y: -7 },
{ x: 2, y: -3 }
]
Conclusion
Point reflection uses the formula P' = 2Q - P to find the symmetric point across a center. This geometric transformation is useful in graphics programming and mathematical applications.
Advertisements
