Sir
Sir

Reputation: 8280

Detect when mouse is reaching perimeter of an ellipse within a certain amount

I have a simple canvas setup which checks mouse position to see if its inside the ellipse or not.

But i would like to check only to see if the mouse is within lets say 15px of the perimeter of the line from either side.

My canvas code is here http://jsfiddle.net/a74fg4fo/

The function in question is:

function check(e){
   //fix mouse position relative to canvas
   var mousePos = relMouseCoords(e,this);

   var x = Math.pow((mousePos.x - offsetX),2) / Math.pow(radius*scaleX,2);
   var y = Math.pow((mousePos.y- offsetY),2) / Math.pow(radius*scaleY,2);

  //check if mouse position is inside shape
   if(x + y <= 1){
        output.innerHTML += ' IN';
   } else {
        output.innerHTML +=  ' OUT';
   }
}

I'm a bit confused on how to base it solely on the perimeter rather than the entire shape.

Upvotes: 2

Views: 233

Answers (1)

adrenalin
adrenalin

Reputation: 1658

A simple approximation would be to have two ellipses, which have that 15px threshold to the original and check that the cursor is in the intersection of those.

I don't have mathematics now to back it up, so this might be a quick and dirty approximation rather than absolute, but check first that it is inside the ellipse you are looking for and then outside the helper that is r = (radius - 15)

Here is your fiddle, updated

function check(e){
   var threshold = 15;
   var mousePos = relMouseCoords(e,this);
   output.innerHTML = mousePos.x +' | ' + mousePos.y


   var x = Math.pow((mousePos.x - centerX),2) / Math.pow((radius + threshold) *scalex,2);
   var y = Math.pow((mousePos.y-centerY),2) / Math.pow((radius + threshold) *scaley,2);

    var inside = false;

   if(x + y <= 1){
        inside = true;
   }

   var x0 = Math.pow((mousePos.x - centerX),2) / Math.pow((radius - threshold)  * scalex, 2);
   var y0 = Math.pow((mousePos.y - centerY),2) / Math.pow((radius - threshold)  * scaley, 2);

    // Inside the inner helper, thus outside threshold
    if (x0 + y0 <= 1) {
        inside = false;
    }

   if (inside) {
        output.innerHTML += ' IN';
   } else {
        output.innerHTML +=  ' OUT';
   }
}

http://jsfiddle.net/a74fg4fo/2/

Upvotes: 2

Related Questions