2

I tried to draw a line with a certain angle in a html canvas. Unfortunately, the line does not appear at the desired angle. Can someone tell me what I am doing wrong?

html code:

<!DOCTYPE html>
<html lang="de">
    <head>
        <title>Test html canvas</title>
    </head>
    <body>
        <canvas id="cumulatedView" width="250" height="250"></canvas>
    </body>
</html>

css code:

canvas{
  background-color: grey;
  background-position: center;
  background-size: 100% 100%;
}

Javascript code:

var angle = 90; // Degree

var c = document.getElementById("cumulatedView");
var ctx = c.getContext("2d");
x1 = 125;
y1 = 125;
length =  100;

x2 = x1 + Math.cos((Math.PI / 180.0) * angle - 90) * length
y2 = y1 + Math.sin((Math.PI / 180.0) * angle - 90) * length

ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();

The following two threads were already very helpful. But I didn't want to answer them because they are a bit older.

JS Canvas - draw line at a specified angle

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

I have uploaded a trial to test on JSFiddle. The problem is there as well. https://jsfiddle.net/zkurqp4x/

I am still quite a beginner with html and Javascript. Thank you for your help.

Ferenc Farkas
  • 23
  • 1
  • 3
  • You are transforming the angle in radians but not the -90. Try this: Math.cos((Math.PI / 180.0) * ( angle - 90)) – enxaneta Feb 28 '19 at 06:37

1 Answers1

7

I assume you are trying to draw a perpendicular line.

Since your angle is degrees. Try this code to calculate (x2,y2).

x2 = x1 + Math.cos(Math.PI * angle / 180) * length;
y2 = y1 + Math.sin(Math.PI * angle / 180) * length;

https://jsfiddle.net/29s5gqu7/1/

Murali Nepalli
  • 1,588
  • 8
  • 17
  • Thank you for your message, your suggested solution works. Unfortunately the angles are 90 degrees rotated (0 degrees is 90 degrees). Do I have to subtract 90 degrees myself or is this a bug in the code? – Ferenc Farkas Feb 28 '19 at 03:28
  • It's not a bug. The coordinates start from top left corner and the angle runs in clockwise direction. that's why you see the line rotating in clockwise direction as you increase the angle from 0. If you want the line to go in anticlock wise direction each time you increase the angle then subtract your angle from 360. – Murali Nepalli Mar 05 '19 at 07:10