【问题标题】:If mouse is inside circle sector? [duplicate]如果鼠标在圆圈内? [复制]
【发布时间】:2014-05-17 13:59:35
【问题描述】:

短版

简而言之,我如何检测鼠标光标是否位于 HTML 5 Canvas 上绘制的圆的扇区内

加长版

我拥有所有这些投票数据,并希望将其显示为饼图,并随着数据的进入而更新,所以我有 PHP 脚本来计算段大小并制作一个通过 $.getScript 加载的 javascript

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();  

}

这是饼图代码的JSfiddle

我之前研究过clickable areas,但不知道如何将其应用于某个领域。

我也考虑过使用ghost canvas background,但不知道如何翻译,因此每个部门都被单独处理。

有没有办法在没有库的情况下做到这一点,或者我应该考虑使用 ChartJs 之类的东西?

【问题讨论】:

  • @bosonix 我以前没见过那个,谢谢
  • 或者干脆在最后定义的路径上使用原生方法ctx.isPointInPath(x, y)(对每个扇区重新定义,无需重绘)。
  • @Epistemex 太棒了

标签: javascript html canvas geometry


【解决方案1】:

下面的代码来自If mouse is inside circle sector?,但经过重构,它可以使用角度而不是点。

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);
}

【讨论】:

  • 我现在有一个主要是working model,谢谢。但我对第二个函数中的角度和第 2 点感到困惑
  • 没关系,现在想通了
  • 发现center.y + radius * Math.sin(angle) 必须是(center.y + radius) * Math.sin(angle),x 也一样。
猜你喜欢
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 2018-11-12
相关资源
最近更新 更多