用数学方法将一个矩形分成四个三角形并确定指针位置

Divide a rectangle into four triangles mathematically and determinate the pointer location

看下图,一个矩形被div分成四个三角形,分别命名为上、右、下、左。

objective是根据三角形的边界来确定指针位置,所以return的值应该是上、右、下、左。

确定指针位置的一种方法是在框中添加四个div,然后使用elementFromPoint确定指针位置。 (here is the example.)

然而,这感觉像是一个 hacky 解决方案,当然必须有一种更优雅的方法来在数学上做到这一点而无需额外的 divs。

已知以下变量:

div 尺寸:

宽度:100px; 高度:50px;

指针位置:

x: 40px y: 15px

有什么建议吗?

如果点的坐标是x和y,你可以计算x处的两条对角线的y值,并将y与它们进行比较:

/**
 * @param {number} x X coordinate of the point
 * @param {number} y Y coordinate of the point
 * @param {number} w Width of the rectangle
 * @param {number} h Height of the rectangle
 * @returns {-1 | 0 | 1 | 2 | 3} -1 = Outside, 0 = Left, 1 = Right, 2 = Top, 3 = Bottom
 */
function pointInRectanglePart(x, y, w, h) {
  const y1 = h * x / w; // y of 1st diagonal at x
  const y2 = h - y1; // y of 2nd diagonal at x
  return (
    x < 0 || w <= x || y < 0 || h <= y ? -1 :
    y < y1 ? (y < y2 ? 2 : 1) : (y < y2 ? 0 : 3)
  );
}

请注意,此函数 returns 四个三角形的数字代码(在函数上方的注释中定义)和 returns -1 如果点在矩形之外。

JSFiddle test page