javascript 用给定的角度和长度从 x,y 画一条线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23598547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw a line from x,y with a given angle and length
提问by Newt-7
In Javascript I want to draw a line from x/y with a given length and angle. I don't want to draw a line from x1/y1 to x2/y2. I have an x/y origin, an angle and a length.
在 Javascript 中,我想用给定的长度和角度从 x/y 画一条线。我不想从 x1/y1 到 x2/y2 画一条线。我有一个 x/y 原点、一个角度和一个长度。
The line needs to sit on top of a standard web page at a specific position.
该行需要位于标准网页顶部的特定位置。
How can I do this?
我怎样才能做到这一点?
Thanks
谢谢
回答by Floris
moveTo(x,y)
defines the starting point of the linelineTo(x,y)
defines the ending point of the line
moveTo(x,y)
定义线的起点 定义线lineTo(x,y)
的终点
So you want something like this:
所以你想要这样的东西:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
x1 = 30;
y1 = 40;
r = 50;
theta = 0.5;
ctx.moveTo(x1, y1);
ctx.lineTo(x1 + r * Math.cos(theta), y1 + r * Math.sin(theta));
ctx.stroke();
where you must make sure that theta
is in radians and that ctx
is defined to be whatever canvas context you want it to be (in the above code, this means you want something like
您必须确保它theta
以弧度表示并且ctx
被定义为您想要的任何画布上下文(在上面的代码中,这意味着您想要类似的东西
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
in your html).
在您的 html 中)。
If theta
is in degrees, you can use Math.cos(Math.PI * theta / 180.0)
and Math.sin(Math.PI * theta / 180.0)
instead of Math.cos(theta)
and Math.sin(theta)
to get the job done...
如果theta
是度数,则可以使用Math.cos(Math.PI * theta / 180.0)
andMath.sin(Math.PI * theta / 180.0)
代替Math.cos(theta)
andMath.sin(theta)
来完成工作...