如果我知道该角度,例如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();