Move a point along an ellipse
I created an ellipse in my canvas and now I need to draw three lines originating from the beginning. As an example, let's say the first row is 90 degrees (vertical), so the point is (0, 10). I need the other two lines to be x pixels from the point in both directions.
I'm sure I haven't described it well enough, but basically what I'm trying to do is point on a known ellipse, find another point x in the distance that lies on the ellipse.
I've tried looking for an ellipse arc but nothing seems to be what I'm looking for.
source to share
For an ellipse:
x = a cos(t)
y = b sin(t)
So:
x/a= cos(t)
t = acos(x/a)
y = b sin(acos(x/a))
Plug in the values a
, b
and x
, and you get y
.
Cm. http://www.mathopenref.com/coordparamellipse.html
Rather rough:
<html>
<head><title>Ellipse</title></head>
<body>
<canvas id="myCanvas" style="position: absolute;" width="400" height="200"></canvas>
<script type="text/javascript">
var a=120;
var b=70;
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var xCentre=c.width / 2;
var yCentre=c.height / 2;
// draw axes
cxt.strokeStyle='blue';
cxt.beginPath();
cxt.moveTo(0, yCentre);
cxt.lineTo(xCentre*2, yCentre);
cxt.stroke();
cxt.beginPath();
cxt.moveTo(xCentre, 0);
cxt.lineTo(xCentre, yCentre*2);
cxt.stroke();
// draw ellipse
cxt.strokeStyle='black';
cxt.beginPath();
for (var i = 0 * Math.PI; i < 2 * Math.PI; i += 0.01 ) {
xPos = xCentre - (a * Math.cos(i));
yPos = yCentre + (b * Math.sin(i));
if (i == 0) {
cxt.moveTo(xPos, yPos);
} else {
cxt.lineTo(xPos, yPos);
}
}
cxt.lineWidth = 2;
cxt.strokeStyle = "#232323";
cxt.stroke();
cxt.closePath();
// draw lines with x=+/- 40
var deltaX=40;
var y1=b*Math.sin(Math.acos(deltaX/a));
cxt.strokeStyle='red';
cxt.beginPath();
cxt.moveTo(xCentre+deltaX, yCentre-y1);
cxt.lineTo(xCentre, yCentre);
cxt.lineTo(xCentre-deltaX, yCentre-y1);
cxt.stroke();
</script>
</body>
(Using http://www.scienceprimer.com/draw-oval-html5-canvas as a framework, since I've never used HTML canvas before.)
source to share
Andrew Morton's answer is adequate, but you can use it with one square root instead of sin
andacos
.
Suppose you have an ellipse centered at the origin with a radius along the x-axis a and a radius along the y-axis b . The equation of this ellipse is
x 2 / a 2 + y 2 / b 2 = 1.
Solving this for y gives
y = ± b sqrt (1 - x 2 / a 2 )
You can choose the appropriate sign. Based on your post, you want to get a positive square root.
Javascript translation:
function yForEllipse(a, b, x) {
return b * Math.sqrt(1 - x*x / a * a);
}
source to share