2

Short Version

In Short, how can I detect if the mouse cursor is inside a sector of a circle drawn on a HTML 5 Canvas

Long Version

I have all this voting data and want to display it as a pie chart that updates as the data comes in, so I have PHP script that works out the segment sizes and makes a javascript that laods via $.getScript

function toRadians(deg) { 
return deg * Math.PI / 180 
 } 

function drawpiechart() { 

ctx.fillStyle='#fdbb30'; 
ctx.beginPath(); 
ctx.moveTo(cx,cy); 
ctx.arc(cx,cy,125,0,toRadians(65.4545454545)); 
ctx.lineTo(cx,cy); 
ctx.closePath(); 
ctx.fill();  

ctx.fillStyle='#0087dc'; 
ctx.beginPath(); 
ctx.moveTo(cx,cy); 
ctx.arc(cx,cy,125,toRadians(65.4545454545),toRadians(98.1818181818)); 
ctx.lineTo(cx,cy); 
ctx.closePath(); 
ctx.fill();  

ctx.fillStyle='#EEEEEE'; 
ctx.beginPath(); 
ctx.moveTo(cx,cy); 
ctx.arc(cx,cy,125,toRadians(98.1818181818),toRadians(360)); 
ctx.lineTo(cx,cy); 
ctx.closePath(); 
ctx.fill();  

}

Heres a JSfiddle of the piechart code.

I've worked out clickable areas before but couldn't figure out how to apply that to a sector.

I also looked at using a ghost canvas background but didn't know how to translate that across so each sector was treated separately.

Is there a way to do this without a library, or should I look at using something like ChartJs ?

Andrei Bozantan
  • 3,781
  • 2
  • 30
  • 40
Rudiger Kidd
  • 498
  • 1
  • 5
  • 23

1 Answers1

2

The code below is from If mouse is inside circle sector? but it is refactored so that it works with angles instead of points.

function isInsideSector(point, center, radius, angle1, angle2) {
  function areClockwise(center, radius, angle, point2) {
    var point1 = {
      x : (center.x + radius) * Math.cos(angle),
      y : (center.y + radius) * Math.sin(angle)
    };
    return -point1.x*point2.y + point1.y*point2.x > 0;
  }

  var relPoint = {
    x: point.x - center.x,
    y: point.y - center.y
  };

  return !areClockwise(center, radius, angle1, relPoint) &&
         areClockwise(center, radius, angle2, relPoint) &&
         (relPoint.x*relPoint.x + relPoint.y*relPoint.y <= radius * radius);
}
Community
  • 1
  • 1
Andrei Bozantan
  • 3,781
  • 2
  • 30
  • 40