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
moveTo(x,y)
defines the starting point of the linelineTo(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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With