Skip to content

Instantly share code, notes, and snippets.

@balint42
Last active January 14, 2023 01:49
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save balint42/b99934b2a6990a53e14b to your computer and use it in GitHub Desktop.
reflect point on line javascript function

Reflect point along line

Javascript function to reflect point p along line through points p0 and p1. Expects three point objects of the type { x: number1, y: number2 } as input and returns the first point p reflected on p0 and p1 as output.

/**
* @brief Reflect point p along line through points p0 and p1
*
* @author Balint Morvai <balint@morvai.de>
* @license http://en.wikipedia.org/wiki/MIT_License MIT License
* @param p point to reflect
* @param p0 first point for reflection line
* @param p1 second point for reflection line
* @return object
*/
var reflect = function(p, p0, p1) {
var dx, dy, a, b, x, y;
dx = p1.x - p0.x;
dy = p1.y - p0.y;
a = (dx * dx - dy * dy) / (dx * dx + dy * dy);
b = 2 * dx * dy / (dx * dx + dy * dy);
x = Math.round(a * (p.x - p0.x) + b * (p.y - p0.y) + p0.x);
y = Math.round(b * (p.x - p0.x) - a * (p.y - p0.y) + p0.y);
return { x:x, y:y };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment