Find a point on perpendicular of a line - math

I have a side of a irregular polygon (x1,y1) (x2,y2) at a angle A and the midpoint of the side (mx, my).
I need to find two points (x3,y3) and (x4,y4) on a perpendicular from A passing through (mx, my), with some offset. So that I could check which point is the inside/outside of the polygon.
I'll use the outside one to show the measurement text of the side of the polygon, e.g 2cms
Click to see Visuals

You dont specify the language, but in almost all of them we have atan2 function for that.
canvas.width = window.innerWidth - 10;
canvas.height = window.innerHeight - 10;
const ctx = canvas.getContext('2d');
const line = [canvas.width/2, canvas.height/2, 10, 10];
const pLen = 100; // Length of perpendicular
function drawOrto(line) {
// line vector
const dx = line[2] - line[0];
const dy = line[3] - line[1];
// center point
const mx = line[0] + dx / 2;
const my = line[1] + dy / 2;
const atan = Math.atan2(dy, dx);
// perpendicular vector
const pdx = - pLen * Math.sin(atan);
const pdy = pLen * Math.cos(atan);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Line
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.moveTo(line[0], line[1]);
ctx.lineTo(line[2], line[3]);
ctx.stroke();
// Perpendicular (draw vector both sides from center)
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.moveTo(mx - pdx / 2, my - pdy / 2);
ctx.lineTo(mx + pdx / 2, my + pdy / 2);
ctx.stroke();
// Dots
ctx.fillStyle = 'red';
ctx.fillRect(line[0] - 1, line[1] - 1, 3, 3);
ctx.fillRect(line[2] - 1, line[3] - 1, 3, 3);
ctx.fillStyle = 'yellow';
ctx.fillRect(mx - 1, my - 1, 3, 3);
ctx.fillStyle = 'green';
ctx.fillRect(mx - pdx / 2 - 1, my - pdy / 2 - 1, 3, 3);
ctx.fillRect(mx + pdx / 2 - 1, my + pdy / 2 - 1, 3, 3);
}
drawOrto(line);
canvas.onmousemove = e => {
line[2] = e.offsetX;
line[3] = e.offsetY;
drawOrto(line);
}
<canvas id=canvas></canvas>

Rotation by a quarter-turn is easy: if you have a vector with coordinates (x, y) and rotate it by a quarter-turn anti-clockwise, the coordinates of the new vector are (-y, x).
To find a point (x5,y5) on the perpendicular, you can rotate point (x2,y2) by a quarter-turn anti-clockwise centered on (mx,my), so that:
x5 - mx = - (y2 - my)
y5 - my = x2 - mx
Then you can choose your two points (x3, y3) and (x4, y4) by renormalizing vector (x5-mx, y5-my) to have the length you want:
x4 - mx = (x5 - mx) * (2 cm) / ((x5-mx)**2 + (y5-my)**2)
y4 - my = (y5 - my) * (2 cm) / ((x5-mx)**2 + (y5-my)**2)
x3 - mx = (x5 - mx) * (-2 cm) / ((x5-mx)**2 + (y5-my)**2)
y3 - my = (y5 - my) * (-2 cm) / ((x5-mx)**2 + (y5-my)**2)

First you have to find the side equation:
y - y1 = (y2-y1)/(x2-x1)*(x-x1)
y = (y2-y1)/(x2-x1) * x1 - (y2-y1)/(x2-x1) * x + y1
Once you have an equation like this y=mx+q (y and x are costants, so you only care about finding m and q) you can find the middle point
M((x1+x2)/2), (y1+y2)/2)
When you have both the equation and the middle point you can choose your offset. Now just find the points that correspond to that offset on the segment
P1(mx + offset, my + (offset * m)) and P2(mx - offset, my - (offset * m))
where m is the one you found in the first equation
Now you have the 2 points
To find out which is inside and which is outside we would need to have more data. You could try for example to bisect the angles to find the middle point of the polygon M1 and check which between P1 and P2 has a distance to M1 so that:
if distance(P1, M1) < distance(M, M1) then P1 is inside
"if the distance between the point and the middle of the polygon is less than the distance between the middle of the polygon and the middle of the side then P1 is inside the polygon"
There are other solutions, but with the data available this is all i can do. Now you just have to turn this explanation into code
LEGEND:
y -> equation constant
x -> equation constant
m -> line inclination
q -> intersection with axis (you really don't need it for this)
M -> middle point of the side mx, my -> coordinates of middle point of the side
P1 -> point on the line with positive offset
P2 -> point on the line with negative offset
M1 -> middle point of the polygon

Related

Tesselation of the circle in OpenGL

I'm having trouble understanding the math behind this function. I would like to hear the logic behind the formulas (especially what is this tangential and radial factor) written here to create points which later (when it send the vec3 array to a function) form a circle in OpenGL.
void doTesselate(const Arc& arc, int slices, std::vector<glm::vec3>& vertices)
{
double dang = (arc.endAngle() - arc.startAngle()) * Deg2Rad;
double radius = arc.radius();
double angIncr = dang / slices;
double tangetial_factor = tan(angIncr);
double radial_factor = 1 - cos(angIncr);
double startAngle = arc.startAngle() * Deg2Rad;
const glm::vec3& center = arc.center();
double x = center.x - radius * cos(startAngle);
double y = center.y - radius * sin(startAngle);
++slices;
for (int ii = 0; ii < slices; ii++) {
vertices.push_back(glm::vec3(x, y, center.z));
double tx = center.y - y;
double ty = x - center.x;
x += tx * tangetial_factor;
y += ty * tangetial_factor;
double rx = center.x - x;
double ry = center.y - y;
x += rx * radial_factor;
y += ry * radial_factor;
}
}
The idea is the following:
Starting from the current point, you go a bit in tangential direction and then back towards the center.
The vector (tx, ty) is the tangent at the current point with length equal to the radius. In order to get to the new angle, you have to move tan(angle) * radius along the tangent. radius is already incorporated in the tangent vector and tan(angle) is the tangetial_factor (you get that directly from tangent's definition).
After that, (rx, ry) is the vector towards the center. This vector has the length l:
cos(angle) = radius / l
l = radius / cos(angle)
We need to find a multiple m of this vector, such that the corrected point lies on the circle with the given radius again. If we just inspect the lengths, then we want to find:
target distance = current distance - m * length of (rx, ry)
radius = radius / cos(angle) - m * radius / cos(angle)
1 = (1 - m) / cos(angle)
cos(angle) = 1 - m
1 - cos(angle) = m
And this multiple is exactly the radial_factor (the amount which you need to move towards the center to get onto the circle).

Given two points, how do I draw a line through them?

Say I have {x:10, y:20} and {x:100, y:40}, if I wanted to draw a line that starts at 10,20 and ends at 100,40 I'd do:
context.beginPath();
context.moveTo(10, 20);
context.lineTo(100, 40);
context.stroke();
But what do I do if I want to draw a line through them? That is the line is longer then the space between the points but it crosses over both points?
You can use "inverse" interpolation - by that I mean instead of interpolate a line with a fraction of [0.0, 1.0] you can use a negative value or value > 1 to get "outside" the line:
From this online demo:
The code is simple, you use the x and y set and interpolate them with a delta, here a fractional value between 0 and 1 where 1 is double length outside one of the points:
function extLine(x1, y1, x2, y2, delta) {
var ox1 = x1 + (x2 - x1) * -delta,
ox2 = x1 + (x2 - x1) * (1 + delta),
oy1 = y1 + (y2 - y1) * -delta,
oy2 = y1 + (y2 - y1) * (1 + delta);
ctx.beginPath();
ctx.moveTo(ox1, oy1);
ctx.lineTo(ox2, oy2);
/// for the demo a couple of markers for the original points
ctx.rect(x1 - 2, y1 - 2, 5, 5);
ctx.rect(x2 - 2, y2 - 2, 5, 5);
ctx.stroke();
}
Instead of a fraction as delta you could calculate the length of the line and then get a fraction from that result so you'll you extend the line in numbers of pixels instead.
Here is a version where you give number of pixels instead:
function extLine2(x1, y1, x2, y2, pixels) {
/// calc fraction based on line length and added pixels
var xd = x2 - x1,
yd = y2 - y1,
len = Math.sqrt(xd * xd + yd * yd),
delta = pixels / len,
/// as before
ox1 = x1 + (x2 - x1) * -delta,
ox2 = x1 + (x2 - x1) * (1 + delta),
oy1 = y1 + (y2 - y1) * -delta,
oy2 = y1 + (y2 - y1) * (1 + delta);
ctx.beginPath();
ctx.moveTo(ox1, oy1);
ctx.lineTo(ox2, oy2);
ctx.rect(x1 - 2, y1 - 2, 5, 5);
ctx.rect(x2 - 2, y2 - 2, 5, 5);
ctx.stroke();
}
Draw a longer line, using one of several alternatives:
Intersect the line with the boundaries of the canvas to obtain endpoints
Intersect the line with the “more orthogonal” canvas boundaries, i.e. if the absolute value of the x difference is less than that of the y difference, intersect with the bottom and top boundary, otherwise with the vertical boundary lines
Extend the line by a fixed and sufficiently large multiple of the difference vector
Extend the line by such a multiple of the difference vector that this extension is of fixed and known size
Which of these is most appropriate depends on your application. Can you rely on a maximal canvas size, or a minimal point distance? If not, then the intersection alternatives are more robust, with the second one being less work.

Drawing rectangle between two points with arbitrary width

I'm trying to draw a line between two (2D) points when the user swipes their finger across a touch screen. To do this, I plan on drawing a rectangle on every touch update between the X and Y of the previous touch update and the X and Y of the latest touch update. This should create a continuous and solid line as the user swipes their finger across the screen. However, I would also like this line to have an arbitrary width. My question is, how should I go about calculating the coordinates I need for each rectangle (x1, y1, x2, y2)?
--
Also: if anyone has any information on how I could then go about applying anti-aliasing to this line it'd be a massive help.
Calculate a vector between start and end points
V.X := Point2.X - Point1.X;
V.Y := Point2.Y - Point1.Y;
Then calculate a perpendicular to it (just swap X and Y coordinates)
P.X := V.Y; //Use separate variable otherwise you overwrite X coordinate here
P.Y := -V.X; //Flip the sign of either the X or Y (edit by adam.wulf)
Normalize that perpendicular
Length = sqrt(P.X * P.X + P.Y * P.Y); //Thats length of perpendicular
N.X = P.X / Length;
N.Y = P.Y / Length; //Now N is normalized perpendicular
Calculate 4 points that form a rectangle by adding normalized perpendicular and multiplying it by half of the desired width
R1.X := Point1.X + N.X * Width / 2;
R1.Y := Point1.Y + N.Y * Width / 2;
R2.X := Point1.X - N.X * Width / 2;
R2.Y := Point1.Y - N.Y * Width / 2;
R3.X := Point2.X + N.X * Width / 2;
R3.Y := Point2.Y + N.Y * Width / 2;
R4.X := Point2.X - N.X * Width / 2;
R4.Y := Point2.Y - N.Y * Width / 2;
Draw rectangle using these 4 points.
Here's the picture:
EDIT: To answer the comments: If X and Y are the same then the line is exactly diagonal and perpendicular to a diagonal is a diagonal. Normalization is a method of making a length to equal to 1, so that the width of your line in this example will not depend on perpendiculars length (which is equal to lines length here).
Easy way (I'll call the "width" the thickness of the line):
We need to calculate 2 values, the shift on the x axis and the shift on the y axis for each of the 4 corners. Which is easy enough.
The dimensions of the line are:
width = x2 - x1
height = y2 - y1
Now the x shift (let's call it xS):
xS = (thickness * height / length of line) / 2
yS = (thickness * width / length of line) / 2
To find the length of the line, use Pythagoras's theorem:
length = square_root(width * width + height * height)
Now you have the x shift and y shift.
First coordinate is: (x1 - xS, y1 + yS)
Second: (x1 + xS, y1 - yS)
Third: (x2 + xS, y2 - yS)
Fourth: (x2 - xS, y2 + yS)
And there you go! (Those coordinates are drawn counterclockwise, the default for OpenGL)
If I understand you correctly, you have two end points say A(x1,y1) and B(x2,y2) and an arbitrary width for the rectangle say w. I assume the end points will be just at the middle of the rectangle's shorter sides meaning the distance of the final rectangles corner coordinates would be w/2 to A and B.
You can compute the slope of the line by;
s1 = (y2 - y1) / (x2 - x1) // assuming x1 != x2
The slope of the shorter sides is nothing but s2 = -1/s1.
We have slope, we have distance and we have the reference points.
We than can derive two equations for each corner point:
For one corner closer to A
C(x3,y3):
(y3 - y1) / (x3 - x1) = s2 // by slope
(y3 - y1)^2 + (x3 - x1)^2 = (w/2)^2 // by distance
replacing (y3 - y1) by a and (x3 - x1) by b yields
a = b * s2 // slope equation
// replace a by b*s2
b^2 * s2^2 + b^2 = (w/2)^2 // distance equaiton
b^2 = (w/2)^2 / (s2^2+1)
b = sqrt((w/2)^2 / (s2^2+1))
we know w and s2 and hence compute b
If b is known, we can deduce x3
x3 = b + x1
and a, as well
a = b * s2
and so y3
y3 = b*s2 + y1
we have one corner point C(x3,y3).
To compute the other corner point closer to A, say D(x4,y4), the slope equation can be constructed as
(y1 - y4) / (x1 - x4) = s2
and the calculations listed above should be applied.
Other two corners can be calculated with the steps listed here replacing A(x1, y1) with B(x2,y2).

Computing the 3D coordinates on a unit sphere from a 2D point

I have a square bitmap of a circle and I want to compute the normals of all the pixels in that circle as if it were a sphere of radius 1:
The sphere/circle is centered in the bitmap.
What is the equation for this?
Don't know much about how people program 3D stuff, so I'll just give the pure math and hope it's useful.
Sphere of radius 1, centered on origin, is the set of points satisfying:
x2 + y2 + z2 = 1
We want the 3D coordinates of a point on the sphere where x and y are known. So, just solve for z:
z = ±sqrt(1 - x2 - y2).
Now, let us consider a unit vector pointing outward from the sphere. It's a unit sphere, so we can just use the vector from the origin to (x, y, z), which is, of course, <x, y, z>.
Now we want the equation of a plane tangent to the sphere at (x, y, z), but this will be using its own x, y, and z variables, so instead I'll make it tangent to the sphere at (x0, y0, z0). This is simply:
x0x + y0y + z0z = 1
Hope this helps.
(OP):
you mean something like:
const int R = 31, SZ = power_of_two(R*2);
std::vector<vec4_t> p;
for(int y=0; y<SZ; y++) {
for(int x=0; x<SZ; x++) {
const float rx = (float)(x-R)/R, ry = (float)(y-R)/R;
if(rx*rx+ry*ry > 1) { // outside sphere
p.push_back(vec4_t(0,0,0,0));
} else {
vec3_t normal(rx,sqrt(1.-rx*rx-ry*ry),ry);
p.push_back(vec4_t(normal,1));
}
}
}
It does make a nice spherical shading-like shading if I treat the normals as colours and blit it; is it right?
(TZ)
Sorry, I'm not familiar with those aspects of C++. Haven't used the language very much, nor recently.
This formula is often used for "fake-envmapping" effect.
double x = 2.0 * pixel_x / bitmap_size - 1.0;
double y = 2.0 * pixel_y / bitmap_size - 1.0;
double r2 = x*x + y*y;
if (r2 < 1)
{
// Inside the circle
double z = sqrt(1 - r2);
.. here the normal is (x, y, z) ...
}
Obviously you're limited to assuming all the points are on one half of the sphere or similar, because of the missing dimension. Past that, it's pretty simple.
The middle of the circle has a normal facing precisely in or out, perpendicular to the plane the circle is drawn on.
Each point on the edge of the circle is facing away from the middle, and thus you can calculate the normal for that.
For any point between the middle and the edge, you use the distance from the middle, and some simple trig (which eludes me at the moment). A lerp is roughly accurate at some points, but not quite what you need, since it's a curve. Simple curve though, and you know the beginning and end values, so figuring them out should only take a simple equation.
I think I get what you're trying to do: generate a grid of depth data for an image. Sort of like ray-tracing a sphere.
In that case, you want a Ray-Sphere Intersection test:
http://www.siggraph.org/education/materials/HyperGraph/raytrace/rtinter1.htm
Your rays will be simple perpendicular rays, based off your U/V coordinates (times two, since your sphere has a diameter of 2). This will give you the front-facing points on the sphere.
From there, calculate normals as below (point - origin, the radius is already 1 unit).
Ripped off from the link above:
You have to combine two equations:
Ray: R(t) = R0 + t * Rd , t > 0 with R0 = [X0, Y0, Z0] and Rd = [Xd, Yd, Zd]
Sphere: S = the set of points[xs, ys, zs], where (xs - xc)2 + (ys - yc)2 + (zs - zc)2 = Sr2
To do this, calculate your ray (x * pixel / width, y * pixel / width, z: 1), then:
A = Xd^2 + Yd^2 + Zd^2
B = 2 * (Xd * (X0 - Xc) + Yd * (Y0 - Yc) + Zd * (Z0 - Zc))
C = (X0 - Xc)^2 + (Y0 - Yc)^2 + (Z0 - Zc)^2 - Sr^2
Plug into quadratic equation:
t0, t1 = (- B + (B^2 - 4*C)^1/2) / 2
Check discriminant (B^2 - 4*C), and if real root, the intersection is:
Ri = [xi, yi, zi] = [x0 + xd * ti , y0 + yd * ti, z0 + zd * ti]
And the surface normal is:
SN = [(xi - xc)/Sr, (yi - yc)/Sr, (zi - zc)/Sr]
Boiling it all down:
So, since we're talking unit values, and rays that point straight at Z (no x or y component), we can boil down these equations greatly:
Ray:
X0 = 2 * pixelX / width
Y0 = 2 * pixelY / height
Z0 = 0
Xd = 0
Yd = 0
Zd = 1
Sphere:
Xc = 1
Yc = 1
Zc = 1
Factors:
A = 1 (unit ray)
B
= 2 * (0 + 0 + (0 - 1))
= -2 (no x/y component)
C
= (X0 - 1) ^ 2 + (Y0 - 1) ^ 2 + (0 - 1) ^ 2 - 1
= (X0 - 1) ^ 2 + (Y0 - 1) ^ 2
Discriminant
= (-2) ^ 2 - 4 * 1 * C
= 4 - 4 * C
From here:
If discriminant < 0:
Z = ?, Normal = ?
Else:
t = (2 + (discriminant) ^ 1 / 2) / 2
If t < 0 (hopefully never or always the case)
t = -t
Then:
Z: t
Nx: Xi - 1
Ny: Yi - 1
Nz: t - 1
Boiled farther still:
Intuitively it looks like C (X^2 + Y^2) and the square-root are the most prominent figures here. If I had a better recollection of my math (in particular, transformations on exponents of sums), then I'd bet I could derive this down to what Tom Zych gave you. Since I can't, I'll just leave it as above.

How to calculate center of an ellipse by two points and radius sizes

While working on SVG implementation for Internet Explorer to be based on its own VML format I came to a problem of translation of an SVG elliptical arc to an VML elliptical arc.
In VML an arc is given by: two angles for two points on ellipse and lengths of radiuses,
In SVG an arc is given by: two pairs of coordinates for two points on ellipse and sizes of ellipse boundary box
So, the question is: How to express angles of two points on ellipse to two pairs of their coordinates.
An intermediate question could be: How to find the center of an ellipse by coordinates of a pair of points on its curve.
Update: Let's have a precondition saying that an ellipse is normally placed (its radiuses are parallel to linear coordinate system axis), thus no rotation is applied.
Update: This question is not related to svg:ellipse element, rather to "a" elliptical arc command in svg:path element (SVG Paths: The elliptical arc curve commands)
So the solution is here:
The parametrized formula of an ellipse:
x = x0 + a * cos(t)
y = y0 + b * sin(t)
Let's put known coordinates of two points to it:
x1 = x0 + a * cos(t1)
x2 = x0 + a * cos(t2)
y1 = y0 + b * sin(t1)
y2 = y0 + b * sin(t2)
Now we have a system of equations with 4 variables: center of ellipse (x0/y0) and two angles t1, t2
Let's subtract equations in order to get rid of center coordinates:
x1 - x2 = a * (cos(t1) - cos(t2))
y1 - y2 = b * (sin(t1) - sin(t2))
This can be rewritten (with product-to-sum identities formulas) as:
(x1 - x2) / (2 * a) = sin((t1 + t2) / 2) * sin((t1 - t2) / 2)
(y2 - y1) / (2 * b) = cos((t1 + t2) / 2) * sin((t1 - t2) / 2)
Let's replace some of the equations:
r1: (x1 - x2) / (2 * a)
r2: (y2 - y1) / (2 * b)
a1: (t1 + t2) / 2
a2: (t1 - t2) / 2
Then we get simple equations system:
r1 = sin(a1) * sin(a2)
r2 = cos(a1) * sin(a2)
Dividing first equation by second produces:
a1 = arctan(r1/r2)
Adding this result to the first equation gives:
a2 = arcsin(r2 / cos(arctan(r1/r2)))
Or, simple (using compositions of trig and inverse trig functions):
a2 = arcsin(r2 / (1 / sqrt(1 + (r1/r2)^2)))
or even more simple:
a2 = arcsin(sqrt(r1^2 + r2^2))
Now the initial four-equations system can be resolved with easy and all angles as well as eclipse center coordinates can be found.
The elliptical curve arc link you posted includes a link to elliptical arc implementation notes.
In there, you will find the equations for conversion from endpoint to centre parameterisation.
Here is my JavaScript implementation of those equations, taken from an interactive demo of elliptical arc paths, using Sylvester.js to perform the matrix and vector calculations.
// Calculate the centre of the ellipse
// Based on http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
var x1 = 150; // Starting x-point of the arc
var y1 = 150; // Starting y-point of the arc
var x2 = 400; // End x-point of the arc
var y2 = 300; // End y-point of the arc
var fA = 1; // Large arc flag
var fS = 1; // Sweep flag
var rx = 100; // Horizontal radius of ellipse
var ry = 50; // Vertical radius of ellipse
var phi = 0; // Angle between co-ord system and ellipse x-axes
var Cx, Cy;
// Step 1: Compute (x1′, y1′)
var M = $M([
[ Math.cos(phi), Math.sin(phi)],
[-Math.sin(phi), Math.cos(phi)]
]);
var V = $V( [ (x1-x2)/2, (y1-y2)/2 ] );
var P = M.multiply(V);
var x1p = P.e(1); // x1 prime
var y1p = P.e(2); // y1 prime
// Ensure radii are large enough
// Based on http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
// Step (a): Ensure radii are non-zero
// Step (b): Ensure radii are positive
rx = Math.abs(rx);
ry = Math.abs(ry);
// Step (c): Ensure radii are large enough
var lambda = ( (x1p * x1p) / (rx * rx) ) + ( (y1p * y1p) / (ry * ry) );
if(lambda > 1)
{
rx = Math.sqrt(lambda) * rx;
ry = Math.sqrt(lambda) * ry;
}
// Step 2: Compute (cx′, cy′)
var sign = (fA == fS)? -1 : 1;
// Bit of a hack, as presumably rounding errors were making his negative inside the square root!
if((( (rx*rx*ry*ry) - (rx*rx*y1p*y1p) - (ry*ry*x1p*x1p) ) / ( (rx*rx*y1p*y1p) + (ry*ry*x1p*x1p) )) < 1e-7)
var co = 0;
else
var co = sign * Math.sqrt( ( (rx*rx*ry*ry) - (rx*rx*y1p*y1p) - (ry*ry*x1p*x1p) ) / ( (rx*rx*y1p*y1p) + (ry*ry*x1p*x1p) ) );
var V = $V( [rx*y1p/ry, -ry*x1p/rx] );
var Cp = V.multiply(co);
// Step 3: Compute (cx, cy) from (cx′, cy′)
var M = $M([
[ Math.cos(phi), -Math.sin(phi)],
[ Math.sin(phi), Math.cos(phi)]
]);
var V = $V( [ (x1+x2)/2, (y1+y2)/2 ] );
var C = M.multiply(Cp).add(V);
Cx = C.e(1);
Cy = C.e(2);
An ellipse cannot be defined by only two points. Even a circle (a special cased ellipse) is defined by three points.
Even with three points, you would have infinite ellipses passing through these three points (think: rotation).
Note that a bounding box suggests a center for the ellipse, and most probably assumes that its major and minor axes are parallel to the x,y (or y,x) axes.
The intermediate question is fairly easy... you don't. You work out the centre of an ellipse from the bounding box (namely, the centre of the box is the centre of the ellipse, as long as the ellipse is centred in the box).
For your first question, I'd look at the polar form of the ellipse equation, which is available on Wikipedia. You would need to work out the eccentricity of the ellipse as well.
Or you could brute force the values from the bounding box... work out if a point lies on the ellipse and matches the angle, and iterate through every point in the bounding box.
TypeScript implementation based on the answer from Rikki.
Default DOMMatrix and DOMPoint are used for the calculations (Tested in the latest Chrome v.80) instead of the external library.
ellipseCenter(
x1: number,
y1: number,
rx: number,
ry: number,
rotateDeg: number,
fa: number,
fs: number,
x2: number,
y2: number
): DOMPoint {
const phi = ((rotateDeg % 360) * Math.PI) / 180;
const m = new DOMMatrix([
Math.cos(phi),
-Math.sin(phi),
Math.sin(phi),
Math.cos(phi),
0,
0,
]);
let v = new DOMPoint((x1 - x2) / 2, (y1 - y2) / 2).matrixTransform(m);
const x1p = v.x;
const y1p = v.y;
rx = Math.abs(rx);
ry = Math.abs(ry);
const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
if (lambda > 1) {
rx = Math.sqrt(lambda) * rx;
ry = Math.sqrt(lambda) * ry;
}
const sign = fa === fs ? -1 : 1;
const div =
(rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p) /
(rx * rx * y1p * y1p + ry * ry * x1p * x1p);
const co = sign * Math.sqrt(Math.abs(div));
// inverse matrix b and c
m.b *= -1;
m.c *= -1;
v = new DOMPoint(
((rx * y1p) / ry) * co,
((-ry * x1p) / rx) * co
).matrixTransform(m);
v.x += (x1 + x2) / 2;
v.y += (y1 + y2) / 2;
return v;
}
Answering part of the question with code
How to find the center of an ellipse by coordinates of a pair of points on its curve.
This is a TypeScript function which is based on the excellent accepted answer by Sergey Illinsky above (which ends somewhat halfway through, IMHO). It calculates the center of an ellipse with given radii, given the condition that both provided points a and b must lie on the circumference of the ellipse. Since there are (almost) always two solutions to this problem, the code choses the solution that places the ellipse "above" the two points:
(Note that the ellipse must have major and minor axis parallel to the horizontal/vertical)
/**
* We're in 2D, so that's what our vertors look like
*/
export type Point = [number, number];
/**
* Calculates the vector that connects the two points
*/
function deltaXY (from: Point, to: Point): Point {
return [to[0]-from[0], to[1]-from[1]];
}
/**
* Calculates the sum of an arbitrary amount of vertors
*/
function vecAdd (...vectors: Point[]): Point {
return vectors.reduce((acc, curr) => [acc[0]+curr[0], acc[1]+curr[1]], [0, 0]);
}
/**
* Given two points a and b, as well as ellipsis radii rX and rY, this
* function calculates the center-point of the ellipse, so that it
* is "above" the two points and has them on the circumference
*/
function topLeftOfPointsCenter (a: Point, b: Point, rX: number, rY: number): Point {
const delta = deltaXY(a, b);
// Sergey's work leads up to a simple system of liner equations.
// Here, we calculate its general solution for the first of the two angles (t1)
const A = Math.asin(Math.sqrt((delta[0]/(2*rX))**2+(delta[1]/(2*rY))**2));
const B = Math.atan(-delta[0]/delta[1] * rY/rX);
const alpha = A + B;
// This may be the new center, but we don't know to which of the two
// solutions it belongs, yet
let newCenter = vecAdd(a, [
rX * Math.cos(alpha),
rY * Math.sin(alpha)
]);
// Figure out if it is the correct solution, and adjusting if not
const mean = vecAdd(a, [delta[0] * 0.5, delta[1] * 0.5]);
const factor = mean[1] > newCenter[1] ? 1 : -1;
const offMean = deltaXY(mean, newCenter);
newCenter = vecAdd(mean, [offMean[0] * factor, offMean[1] * factor]);
return newCenter;
}
This function does not check if a solution is possible, meaning whether the radii provided are large enough to even connect the two points!

Resources