Skip to content Skip to sidebar Skip to footer

Validate If Mouse Position Is Within Rotated Rectangle In HTML5 Canvas

I am trying to use the HTML5 canvas features. I set up a rectangle on the canvas and it is rotated. It is not returning back a true when I click inside the rotated rectangle. Perh

Solution 1:

Yes, you are tripping on the solution, treat your rectangle as a polygon and you don't have to worry about doing rotation, also you can have more complex shapes than rectangles.

I'm using the ray-casting algorithm: https://github.com/substack/point-in-polygon/blob/master/index.js
With that, all we need to do is check if the mouse is inside the polygon, that is all.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext("2d");
const rect = canvas.getBoundingClientRect();

const poly = [[89, 9], [13, 19], [19, 56], [98, 36], [89, 9]]

function draw(p) {
  p.map(x => ctx.lineTo(x[0], x[1]));
  ctx.stroke();
}

function inside(p, vs) {
  var inside = false;
  for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
    var xi = vs[i][0], yi = vs[i][1];
    var xj = vs[j][0], yj = vs[j][1];
    var intersect = ((yi > p[1]) != (yj > p[1])) && (p[0] < (xj - xi) * (p[1] - yi) / (yj - yi) + xi);
    if (intersect) inside = !inside;
  }
  return inside;
};

draw(poly)
canvas.addEventListener('mousemove', function(evt) {
  ctx.clearRect(100, 0, canvas.width, canvas.height);
  let x = inside([ evt.clientX - rect.left, evt.clientY - rect.top ], poly)
  ctx.fillText(x, 110, 20);
}, false);
<canvas id="canvas"></canvas>

I did it on mousemove so you can see the change right away...
but same can be applied to any event you like


Post a Comment for "Validate If Mouse Position Is Within Rotated Rectangle In HTML5 Canvas"