javascript - 检测 HTML5 Canvas 上圆圈上的鼠标点击

标签 javascript html canvas click mouseevent

我是 Canvas 新手,我正在尝试聆听鼠标点击我之前在 Canvas 上绘制的圆圈的声音。当我单击圆圈时,我试图更改圆圈的颜色(可能更改为绿色)。

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');


var radius = 15;
for (var i = 0; i < 600; i += 100) {
  var x = 100 + i;
  var y = 100;
  draw_circle(i, x, y, radius);
}

function draw_circle(ID, x, y, radius) {
  context.beginPath();
  context.arc(x, y, radius, 0, Math.PI * 2, false);
  context.fillStyle = 'red';
  context.fill();
  context.lineWidth = 3;
  context.strokeStyle = 'black';
  context.stroke();
  context.closePath();

}
<!DOCTYPE HTML>
<html>

<head>
  <style>
    html,
    body {
      width: 100%;
      height: 100%;
      margin: 0px;
    }
  </style>
</head>

<body>
  <canvas id="myCanvas" width="700" height="700"></canvas>

</body>

</html>

最佳答案

只需再次添加圆弧路径并使用 isPointInPath() 与鼠标位置即可。一次只能测试一条弧,但清除和添加新路径的速度很快。循环执行此操作。

示例

var c = document.querySelector("canvas"), ctx = c.getContext("2d");

getArc(50, 50, 40);
ctx.fill();

c.onclick = function(e) {
  var rect = this.getBoundingClientRect(),   // get abs. position of canvas
      x = e.clientX - rect.left,             // adjust mouse-position
      y = e.clientY - rect.top;
  
  getArc(50, 50, 40);                        // get path wo/ filling/stroking it
  if (ctx.isPointInPath(x, y)) alert("Clicked");
};

function getArc(x, y, r) {
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI*2);
  ctx.closePath();
}
<canvas></canvas>

另一种方法是使用数学和三 Angular 学:

// at this point we have the mouse position, so:
var dx = x - arcX,
    dy = y - arcY,
    dist = Math.abs(Math.sqrt(dx*dx + dy*dy));

if (dist <= radius) { ...clicked... };

提示:您可以使用 r2 来跳过距离平方。

关于javascript - 检测 HTML5 Canvas 上圆圈上的鼠标点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30770501/

相关文章:

javascript - 将带空格的字符串传递给 javascript

javascript - 将数据加载到我不知道列的数据表中

html - 如何从网络应用程序访问手机的相机?

javascript - 如何重新缩放图像以使用 Canvas 绘制?

javascript - 随着质量增加,速度下降

java - 安卓自定义进度条

javascript - 黑色文本 - 黑色背景时为白色

javascript - 是否可以使用javascript加载truetype字体

html - HAML 和 HTML - 无法正确复制

javascript - 在不带括号的 HTML 页面中显示用户角色