Ferenc Farkas
Ferenc Farkas

Reputation: 23

Draw a line with specific angle in a html canvas

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.

Upvotes: 2

Views: 5193

Answers (1)

Murali Nepalli
Murali Nepalli

Reputation: 1618

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/

Upvotes: 7

Related Questions