沿椭圆移动一个点

Ada*_*Dev 4 javascript math drawing ellipse

我在画布上创建了一个椭圆,现在我需要绘制三条源于原点的线条.举个例子,假设第一行是90度(垂直),所以点是(0,10).我需要另外两条线在两个方向上距离点x个像素.

我确定我没有足够好地描述这一点,但基本上我要做的是从已知椭圆上的一个点,找到位于椭圆上的另一个距离x距离.

我试过寻找一个椭圆弧,但似乎没有什么适合我想要的东西.

And*_*ton 7

对于椭圆:

x = a cos(t)
y = b sin(t)
Run Code Online (Sandbox Code Playgroud)

所以:

x/a= cos(t)
t = acos(x/a)
y = b sin(acos(x/a))
Run Code Online (Sandbox Code Playgroud)

插上你的价值观a,bx你会得到y.

请参阅http://www.mathopenref.com/coordparamellipse.html

相当粗略:

<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>
Run Code Online (Sandbox Code Playgroud)

(使用http://www.scienceprimer.com/draw-oval-html5-canvas作为基础,因为我以前从未使用过HTML canvas.)


rob*_*off 5

Andrew Morton's answer is adequate, but you can it with one square root instead of a sin and an acos.

Suppose you have an ellipse centered at the origin, with a radius along the X-axis of a and a radius along the Y-axis of b. The equation of this ellipse is

x2/a2 + y2/b2 = 1.

Solving this for y gives

y = ± b sqrt(1 - x2/a2)

您可以选择合适的标志。根据您的帖子,您需要正平方根。

翻译成 Javascript:

function yForEllipse(a, b, x) {
    return b * Math.sqrt(1 - x*x / a * a);
}
Run Code Online (Sandbox Code Playgroud)