View Full Version : Ellipse calculation

07-07-2002, 06:10 AM
I need a function (it needn't be in JavaScript) that calculates the distance of a point from the center of an ellipse given:

The coordinates of the bounding rectangle of the ellipse, and
The position of a point relative to the top-left corner of the ellipse's bounding rectangle.

The distance must be in units.

07-07-2002, 06:41 AM
LOL....do a search online,,,,,,,,

sounds like you want us to do an assignment......

07-07-2002, 03:26 PM
Maybe the getBoundingClientRect() (http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/getboundingclientrect.asp) method will help?

Hope that helps!

Happy coding! :)

07-07-2002, 07:32 PM
Well, given you know the rectangle touching the 2 vertices and the 2 covertices:

var v1 = [leftTopX, (leftTopY + leftBottomY) / 2];
var v2 = [rightTopX, (rightTopY + rightBottomY) / 2];

var cv1 = [(leftTopX + rightTopX) / 2, rightTopY];
var cv2 = [(leftBottomX + rightBottomX) / 2, rightBottomY];

Now, this is assuming that a^2 is under x in the equation, otherwise the cv's would be the v's, and vice versa. You can find this out via:

rightTopX - leftTopX > leftTopY - leftBottomY;

If true, the general equation is (x-h)^2/a^2 + (y-k)^2/b^2, if false b^2 goes under x, and a^2 under y.

From the vertices and covertices, you can generate the equation:

var h = (leftTopX + rightTopX) / 2;
var k = (leftTopY + leftBottomY) / 2;

var a = [v1[0] - h, v2[0] - h];
a = (a[0] > a[1]) ? a[0] : a[1];

var b = [cv1[1] - k, cv2[1] - k];
b = (b[0] > b[1]) ? b[0] : b[1];

var eqn = function(x,y) {
return Math.pow((x-h), 2) / Math.pow(a, 2) + Math.pow((y-k), 2) / Math.pow(b, 2);

Remember to take into account orientation, in which case if the check above proves false, you need to switch the denominators.

Also, this does not take into account possible rotation....

And some of the above might be *slightly* inaccurate, due to fast typing or it being a little while, but I'm pretty sure it seems correct.

07-07-2002, 09:36 PM
Thanks there.

I have another question: I need a function that calculates the radius of an ellipse at an arbitrary angle (in degrees) given the ellipse's bounding rectangle.

07-07-2002, 09:50 PM
Actually, you don't need to worry about the ellipse. You've got the bounding rectangle so you just need to (1) find the center of that rectangle (which will be the same as the center of the ellipse) then (2) find the distance from that center point to the given point.

Since the coordinates of the point are given relative to the top, left corner of the bounding rectangle, you can simplify it even more by just using the rectangle width and height.

So the equation looks like:

d = sqrt((x - w/2)^2 + (y - h/2)^2)

where (x,y) is the point and w and h are the width and height of the bounding rectangle.

In JavaScript syntax:

d = Math.sqrt(Math.pow(x-w/2, 2) + Math.pow(y-h/2, 2));