Search code examples
javascriptcanvashtml5-canvas2ddrawing

How do I check if my mouse coordinates hover over an ellipse shape?


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?


Solution

  • 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