javascript - 从向量和内部 Angular 找到矩形的边缘

标签 javascript vector geometry 2d

在 fiddle 示例中:https://jsfiddle.net/krazyjakee/uazy86m4/您可以在显示为蓝色方 block 的矢量点下方拖动鼠标。您将看到该线绘制了一条从矢量开始、通过鼠标并到达视口(viewport)边缘的路径,其中显示绿色方 block ,表明它已找到边缘。但是,在矢量上方,绿色方 block 消失,因为它无法检测到视口(viewport)的边缘。

这是我当前用来检测边缘的逻辑。

const angle = Math.atan2(mouse.y - vectorCenter.y, mouse.x - vectorCenter.x);

const cosAngle = Math.abs(Math.cos(angle));
const sinAngle = Math.abs(Math.sin(angle));

const vx = (viewport.width - vectorCenter.x) * sinAngle;
const vy = (viewport.height - vectorCenter.y) * cosAngle;

const vpMagnitude = vx <= vy ?
    (viewport.width - vectorCenter.x) / cosAngle :
    (viewport.height - vectorCenter.y) / sinAngle;

const viewportX = vectorCenter.x + Math.cos(angle) * vpMagnitude;
const viewportY = vectorCenter.y + Math.sin(angle) * vpMagnitude;

const viewPortEdge = {
    x: viewportX,
    y: viewportY,
};

请帮我弄清楚如何正确检测视口(viewport)上边缘的位置。

最佳答案

我没有研究为什么这对于顶部会失败,因为有比处理 Angular 更简单的方法。您可以通过一些简单的向量计算来获得位置。

首先,为了明确起见并防止将任何值硬编码到计算中,我扩展了您的视口(viewport)

const viewport = {
  x: 0,
  y: 0,
  width: window.innerWidth,
  height: window.innerHeight,

  get left(){ return this.x },
  get right(){ return this.x + this.width },
  get top(){ return this.y },
  get bottom(){ return this.y + this.height },
};

现在计算:

//prevent division by 0
const notZero = v => +v || Number.MIN_VALUE;

let vx = mouse.x - vectorCenter.x;
let vy = mouse.y - vectorCenter.y;

//that's why I've extended the viewport, so I don't have to hardcode any values here
//Math.min() to check wich border I hit first, X or Y
let t = Math.min(
  ((vx<0? viewport.left: viewport.right) - vectorCenter.x) / notZero(vx),
  ((vy<0? viewport.top: viewport.bottom) - vectorCenter.y) / notZero(vy)
);

const viewPortEdge = {
  x: vectorCenter.x + vx * t,
  y: vectorCenter.y + vy * t,
};

so t 是我必须缩放 mousevectorCenter 之间的向量以击中最近边缘的因素特定方向。

关于javascript - 从向量和内部 Angular 找到矩形的边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48614330/

相关文章:

java - 在android中的textview中将 vector drawable设置为side drawable

c# - 子对象未在父对象上实例化

html - 如何配置 Spotify 嵌入式播放列表?

javascript - Angular Material md-select 空值验证不起作用

javascript - Meteor 和 MongoDB 地理空间 - 边界 - $within

javascript - 正确使用 AngularJS 的 $sanitize 服务?

javascript - 如何获取strong标签中写入的内容?

c++ - c++中的 vector 下标超出范围错误

opengl - OpenGL立方体贴图中的面约定

ruby 数学 gem