javascript - 试图以已知角度在画布单位圆中显示一条线
问题描述
如果我知道角度,比如 30 度,我想在象限中显示一条具有该角度的线。我努力了:
let angle = 30;
ctx.moveTo(canvas.width/2, canvas.height/2); //Center point
ctx.lineTo(Math.cos(angle), Math.sin(angle)); // x and y?; I need the distance?
听着,Trig 对我来说确实是一个新概念,我会很感激任何建议。这是我的画布...
let canvas = document.getElementById("myCanvas"); // width and height are 400
let ctx = canvas.getContext("2d");
ctx.beginPath();
// The Vertical line to create quadrants
ctx.moveTo((canvas.width/2),0);
ctx.lineTo(canvas.width/2, canvas.height);
// The Horizontal Line to create quadrants
ctx.moveTo(0, canvas.height/2);
ctx.lineTo((canvas.width), canvas.height/2);
// The circle contained in my canvas
ctx.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, 2 * Math.PI);
ctx.stroke(); // Make line visible, otherwise for shapes use stroke
// Radians to degrees
function toDegrees(radians){
return radians * Math.PI/180
}
解决方案
首先,我发现先转换弧度然后画线更容易。请记住,单位圆坐标的 x 和 y 值范围从 -1 到 1。我们将其放大,因此要获得画布上的实际位置,我们需要做两件事:
1) 将单位圆坐标乘以中心坐标。2)将中心坐标添加到该值
我使用了红色的描边样式,这样您可以更好地看到它:
完整代码
let canvas = document.getElementById('myCanvas')
let ctx = canvas.getContext('2d')
canvas.width = 512;
canvas.height = 512;
ctx.beginPath();
// The Vertical line to create quadrants
ctx.moveTo((canvas.width/2),0);
ctx.lineTo(canvas.width/2, canvas.height);
// The Horizontal Line to create quadrants
ctx.moveTo(0, canvas.height/2);
ctx.lineTo((canvas.width), canvas.height/2);
// The circle contained in my canvas
ctx.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, 2 * Math.PI);
ctx.stroke(); // Make line visible, otherwise for shapes use stroke
//Degrees to radians
function toRadians(degrees) {
return (degrees * Math.PI)/180
}
//Angle in degrees
let angle = 315;
//Angle in Radians
let angleToRad = toRadians(angle)
//Changes the color to red
ctx.strokeStyle = 'red'
//Starts a new line
ctx.beginPath();
ctx.moveTo(canvas.width/2, canvas.height/2); //Center point
ctx.lineTo((canvas.width/2) + (Math.cos(angleToRad) * canvas.height / 2), (canvas.height/2) - (Math.sin(angleToRad) * canvas.height / 2));
ctx.stroke();
只是我添加的东西:
//Degrees to radians
function toRadians(degrees) {
return (degrees * Math.PI)/180
}
//Angle in degrees
let angle = 315;
//Angle in Radians
let angleToRad = toRadians(angle)
//Changes the color to red
ctx.strokeStyle = 'red'
//Starts a new line
ctx.beginPath();
ctx.moveTo(canvas.width/2, canvas.height/2); //Center point
ctx.lineTo((canvas.width/2) + (Math.cos(angleToRad) * canvas.height / 2), (canvas.height/2) - (Math.sin(angleToRad) * canvas.height / 2));
ctx.stroke();
推荐阅读
- c# - 如何在 DataGridView 中仅显示特定行
- security - Falcon 传感器无法启动代理
- dialogflow-es - 从意图异步触发实现 webhook?
- python - 使用 Keras (PIL) 和 TensorFlow 调整图像大小之间的不一致?
- java - 使用 JColorChooser 绘图
- github - 我想在投资组合中展示和分享我的 React.js 应用
- reactjs - 如果我将 kubernetes 部署扩展到 3,前端应用程序会显示一个空白页面
- ruby-on-rails - f.simple_form 中与 current_user 的关联
- javascript - 编辑后以 PDF 格式发送谷歌工作表
- x86 - 当使用带有 AVX-512 加载和存储的屏蔽寄存器时,是否会因对屏蔽元素的无效访问而引发故障?