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. /
I am still quite a beginner with html and Javascript. Thank you for your help.
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/zkurqp4x/
I am still quite a beginner with html and Javascript. Thank you for your help.
Share Improve this question asked Feb 27, 2019 at 22:21 Ferenc FarkasFerenc Farkas 231 silver badge3 bronze badges 1- You are transforming the angle in radians but not the -90. Try this: Math.cos((Math.PI / 180.0) * ( angle - 90)) – enxaneta Commented Feb 28, 2019 at 6:37
1 Answer
Reset to default 7I 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/29s5gqu7/1/