0

This question is independent from output but for the sake of simplicity we'll keep the problem to the HTML canvas. I have an oval / ellipse which I want to highlight when you hover over it with your mouse. Before I was using a piece of code as described in this question (mouseover circle HTML5 canvas).

Pseudo code;


const circle = { x: 10, y:10, radius:5 };
const distanceBetween: (point1, point2) => {
    var a = point1.x - point2.x;
    var b = point1.y - point2.y;
    return  Math.sqrt( a*a + b*b );
}

var radius = distanceBetween({x: mouse.x, y: mouse.x}, {x: circle.x, circle.y});

// If radius is below 5, mouse is on top of the circle.

But because the radius for x & y are different for this oval shape. Just using the radius is insufficient. I have been experimenting by isolating the problem with the x-radius and the y-radius separately. But I just can not find the missing link to resolve the problem.

var ellipse = {cx: 10, cy:10, rx: 5, ry:10}

What kind of formula do I need to check if my mouse x/y coordinates are hovering over the ellipse?

user007
  • 1,557
  • 3
  • 16
  • 24
  • so you have the ellipse center and which other informations about the ellipse? – Alberto Sinigaglia Aug 05 '20 at 18:18
  • I have x,y coordinates of the ellipse. Plus the x radius & the y radius. The ellipse object looks like the SVG element. – user007 Aug 05 '20 at 18:22
  • 1
    use this formula https://math.stackexchange.com/questions/76457/check-if-a-point-is-within-an-ellipse#:~:text=The%20region%20(disk)%20bounded%20by,it%20is%20outside%20the%20ellipse. – Alberto Sinigaglia Aug 05 '20 at 18:24

1 Answers1

0
var ellipse = {cx: 10, cy:10, rx: 5, ry:10}
var distance = Math.pow(mouse.x - ellipse.cx, 2) / Math.pow(ellipse.rx, 2) + Math.pow(mouse.y - ellipse.cy,2) / Math.pow(ellipse.ry,2);

// distance < 1 is everything within the ellipse.
// distance > 1 is everything outside the ellipse.

Source: https://math.stackexchange.com/a/76463/545328

Thank you @Berto99

user007
  • 1,557
  • 3
  • 16
  • 24