首页 > 解决方案 > 试图以已知角度在画布单位圆中显示一条线

问题描述

如果我知道角度,比如 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
}

标签: javascriptcanvastrigonometry

解决方案


首先,我发现先转换弧度然后画线更容易。请记住,单位圆坐标的 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();

推荐阅读