如何在 javascript 中使用切线获取角度?

How to get an angle by using tangent in javascript?

红圈是已知角度130°,然后我想用红圈的x和y从中心到130°画海军线,但看起来我错过了计算。

目前,海军线的角度反映了红线的角度,如果我在第 13 行的 *diffX * 添加减号 ➖,它将按预期工作,但为什么我需要自己做,为什么第 10 和 13 行的计算不能计算出 x 应该是负 ➖ 还是正。

我不知道我哪里错了..任何 help/suggestions 不胜感激!

let ctx, W = innerWidth,
  H = innerHeight;

// params for the red circle
let hypothenus = 100;
let knownAngle = (-130 * Math.PI) / 180;
let x = (W / 2) + Math.cos(knownAngle) * hypothenus;
let y = (H / 2) + Math.sin(knownAngle) * hypothenus;

// params for navy line
let diffX = x - (W / 2);
let diffY = (H / 2) - y;
let dist = Math.hypot(diffX, diffY); // pythagoras
let unknownAngle = -Math.atan2(diffY, diffX);
let newX = (W / 2) + Math.cos(unknownAngle) * dist;
let newY = (H / 2) + Math.sin(unknownAngle) * dist;

let angInDegree1 = ~~Math.abs(knownAngle * 180 / Math.PI);
let angInDegree2 = ~~Math.abs(unknownAngle * 180 / Math.PI) | 0;

const msg = document.getElementById("msg")
msg.innerHTML = `Hypothenus1: ${hypothenus}, angle: ${angInDegree1}<br>`;
msg.innerHTML +=`Hypothenus2: ${dist},  angle: ${angInDegree2}`;

// everything to be rendered to the screen
const update = () => {
  if (ctx == null) return;

  // drawing the red line
  draw.line([W / 2, 0], [W / 2, H], 6, "red");
  draw.line([0, H / 2], [W, H / 2], 6, "red");

  // the red circle
  draw.circle([x, y], 10, "red");
  // draw line
  draw.line([W / 2, H / 2], [newX, newY], 4, "navy");
}

// utility object for drawing
const draw = {
  line(from, to, width, color) {
    with(ctx) {
      beginPath();
      lineWidth = width;
      strokeStyle = color;
      moveTo(...from);
      lineTo(...to);
      stroke();
      closePath();
    }
  },

  circle(pos, radius, color) {
    ctx.beginPath();
    ctx.fillStyle = color;
    ctx.arc(...pos, radius, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();
  }
}

// init function
const init = () => {
  ctx = document.querySelector("#cvs").getContext("2d");
  W = ctx.canvas.width = innerWidth;
  H = ctx.canvas.height = innerHeight;

  update();
}

window.addEventListener("load", init);
<div id="msg"></div>
<canvas id="cvs"></canvas>

看来你使用的缺点太多了。

首先,你定义角度-130度,接近-3Pi/4。这个角度的余弦值和正弦值约为 -0.7,使用 hypothenus = 100,我们得到 x =W/2-70, y = H/2-70

diffX = x - W/2 = -70
diffY = y - H/2 = -70
atan2(-70, -70) gives -2.3561 radians = -3/4*Pi = -135 degrees

当你改变diffY的符号时(注意 - diffY公式是错误的,不是difX一个!),你进行反思反对 OX 轴,并更改角度符号 - 这就是为什么需要 Math.atan2 之前的另一个减号

更正后的代码:

let diffX = x - (W / 2);
let diffY = y - (H / 2);
let dist = Math.hypot(diffX, diffY); // pythagoras
let unknownAngle = Math.atan2(diffY, diffX);