在 html 画布中绘制具有特定角度的线

Fer*_*kas 2 javascript canvas

我尝试在 html 画布中画一条具有一定角度的线。不幸的是,这条线没有以所需的角度出现。有人可以告诉我我做错了什么吗?

html代码:

<!DOCTYPE html>
<html lang="de">
    <head>
        <title>Test html canvas</title>
    </head>
    <body>
        <canvas id="cumulatedView" width="250" height="250"></canvas>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

CSS代码:

canvas{
  background-color: grey;
  background-position: center;
  background-size: 100% 100%;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript 代码:

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();
Run Code Online (Sandbox Code Playgroud)

以下两个线程已经非常有帮助了。但我不想回答他们,因为他们年纪大了一些。

JS Canvas - 以指定角度画线

以给定的角度和长度从 x,y 画一条线

我已经上传了一个试用版来在 JSFiddle 上进行测试。问题也在那里。 https://jsfiddle.net/zkurqp4x/

我对 html 和 Javascript 仍然是一个初学者。感谢您的帮助。

Mur*_*lli 7

我假设您正在尝试画一条垂直线。

因为你的角度是度数。尝试使用此代码来计算 (x2,y2)。

x2 = x1 + Math.cos(Math.PI * angle / 180) * length;
y2 = y1 + Math.sin(Math.PI * angle / 180) * length;
Run Code Online (Sandbox Code Playgroud)

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