gpt4 book ai didi

javascript - 在 html Canvas 中绘制具有特定 Angular 线

转载 作者:行者123 更新时间:2023-12-02 14:52:27 25 4
gpt4 key购买 nike

我试图在 html Canvas 中以特定 Angular 绘制一条线。不幸的是,这条线没有以所需的 Angular 出现。谁能告诉我我做错了什么?

html代码:

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

CSS 代码:

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

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();

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

JS Canvas - draw line at a specified angle

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

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

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

最佳答案

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

因为你的 Angular 是度数。试试这段代码来计算 (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/

关于javascript - 在 html Canvas 中绘制具有特定 Angular 线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54915438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com