cyrus-d
cyrus-d

Reputation: 843

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

Looking at the picture below, a rectangle has been divided into four triangles and named top, right, bottom, and left.

The objective is to determine the pointer location based on the triangle boundaries, so the return value should be top, right, bottom, left.

enter image description here

One way to determine the pointer location is to add four divs to the box and use elementFromPoint to determine the pointer location. (here is the example.)

However, it feels like a hacky solution, Surely there must be a more elegant way to do this mathematically without additional divs.

Following variables are known:

div dimantion:

width: 100px; height: 50px;

Pointer Location:

x: 40px y: 15px

Any suggestion?

Upvotes: 1

Views: 1160

Answers (1)

kol
kol

Reputation: 28688

If the point's coordinates are x and y, you can calculate the y values of the two diagonals at x, and compare y to them:

/**
 * @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)
  );
}

Note that this function returns number codes for the four triangles (defined in the comment above the function) and returns -1 if the point is outside the rectangle.

JSFiddle test page

Upvotes: 4

Related Questions