如果我知道该角度,例如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();
关于javascript - 尝试在 Canvas 单位圆中以已知 Angular 显示一条线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59217963/