尝试用给定角度计算鼠标 x 或 y(或两者的比率)以给出距离

Trying to calculate mouse x or y (or ratio of both) with given angle to give a distance

我有拖动事件之前和期间的 xy 坐标,this.xthis.y```` are the current coordinates,this.lastXandthis.lastY``` 是原点.

我需要做的是给出源元素的弧度,确定使用哪个鼠标坐标,IE 如果角度为 0,则使用 x 坐标给出 "distance",如果度数为90 然后使用 y 坐标

如果弧度为 0.785398,则需要同时使用 x 和 y。

我有一个轴的以下代码,但这只会翻转 y 坐标

        let leftPosition;
        if (this.walls[this.dragItem.wall].angle < Math.PI / 2) {
          leftPosition = Math.round((-(this.y - this.lastY) / this.scale + this.dragItem.origin.left));
        } else {
          leftPosition = Math.round(((this.y - this.lastY) / this.scale + this.dragItem.origin.left));
        }

我这里有一个例子https://engine.owuk.co.uk

我需要做的是通过计算 leftPosition 来让弧度指示使用什么 x 或 y 坐标来控制项目的拖动,我一直在失去理智试图让它工作:(

Math.sin和Math.cos是你需要的,这里有一个例子

<canvas id="c" width=300 height=150></canvas>
<script>
  const ctx = document.getElementById('c').getContext('2d');

  function drawShape(size, angle, numPoints, color) {
    ctx.beginPath();
    for (j = 0; j < numPoints; j++) {
      a = angle * Math.PI / 180
      x = size * Math.sin(a)
      y = size * Math.cos(a)
      ctx.lineTo(x, y);
      angle += 360 / numPoints
    }
    ctx.fillStyle = color;
    ctx.fill();
  }

  ctx.translate(80, 80);
  drawShape(55, 0, 7, "green");
  drawShape(45, 0, 5, "red");
  drawShape(35, 0, 3, "blue");

  ctx.translate(160, 0);
  drawShape(55, 15, 7, "green");
  drawShape(45, 35, 5, "red");
  drawShape(35, 25, 3, "blue");
</script>

我能够解决我的问题

let position;

const sin = Math.sin(this.walls[this.dragItem.wall].angle);
const cos = Math.cos(this.walls[this.dragItem.wall].angle);

position = Math.round(((this.x - this.lastX) / this.scale * cos + (this.y - this.lastY) / this.scale * sin) + this.dragItem.origin.left);

这是您问题的理论答案。

以最简单的方式,您有一个线段内的对象,该对象必须相对于鼠标的位置移动,但受线段向量的约束。

这是一个可视化表示:

所以鼠标在红色箭头处,蓝色圆圈需要移动到浅蓝色。
(直线到点的最短距离)

我们该怎么做?
让我们为该图像添加我们能做的一切:

线段和鼠标组成一个三角形,我们可以计算三角形各边的长度。
两点之间的距离是一个简单的毕达哥拉斯计算:
https://ncalculators.com/geometry/length-between-two-points-calculator.htm

然后我们需要以我们的线段为底边的三角形的高度:
https://tutors.com/math-tutors/geometry-help/how-to-find-the-height-of-a-triangle

这将为我们提供从鼠标到线段的距离,我们通过添加线段的角度 + 90 度(或 PI/2 弧度)来知道角度,这就是我们所需要的来计算我们浅蓝色圆圈的位置。

当然,我们还需要添加一些 min/max 数学运算以不超出段的边界,但如果您做到了这一点,那应该很容易选择。