Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a line from x,y with a given angle and length [duplicate]

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.

The line needs to sit on top of a standard web page at a specific position.

How can I do this?

Thanks

like image 892
Newt-7 Avatar asked May 11 '14 22:05

Newt-7


1 Answers

moveTo(x,y) defines the starting point of the line
lineTo(x,y) defines the ending point of the line

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

<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>

in your 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...

like image 78
Floris Avatar answered Nov 11 '22 17:11

Floris