如何使用 JavaScript 单击 canvas 中的一个圆圈

How to click one circle among others in canvas using JavaScript

我想从一组圆圈中分别单击每个圆圈。因为我想在被点击后为每个圈子做不同的任务。虽然多个圆圈存储在数​​组 circles[] 中,但当我单击圆圈时,如果没有一个圆圈,则不会显示警报,并且会显示警报 5 次。我假设这是随机绘制的最后一个圆圈,只有这个圆圈有点击效果! 有人可以帮我解决这个问题吗?

const canvas = document.getElementById('flower');
const ctx = canvas.getContext('2d');
var offsetX = canvas.offsetLeft;
var offsetY = canvas.offsetTop;
var circles = [];

function main(){
    if (typeof document !== 'undefined') {
            var r = 20; 
            for (var j=0; j<5; j++){
                var cx = random()*(canvas.width);
                var cy = random()*(canvas.height);
                var r = 25;
                var color = "rgb(" + Math.floor(random() * 256) + "," + Math.floor(random() * 256)
                            + "," + Math.floor(random() * 256) + ")";
                ctx.beginPath();
                ctx.arc(cx, cy, r, 0, 2 * Math.PI);
                ctx.fillStyle = color;
                ctx.fill();
                ctx.closePath();
                var obj = {}; 
                obj['x'] = cx;
                obj['y'] = cy;
                circles.push(obj);
                
            }
            //console.log(circles); 5 circles are stored in circles[]
            circles.forEach(function(entry){
            canvas.addEventListener('click', function(e) {
                    var clickX = e.clientX - offsetX;
                    var clickY = e.clientY - offsetY;
                    var dx = cx - clickX;
                    var dy = cy - clickY;
                    if (dx * dx + dy * dy <= r * r) {
                        alert("you are inside the circle");
                    }
                });
            });
                                
        }
}



    var seed = 1;
    function random() {
        var x = Math.sin(seed++) * 10000;
        return x - Math.floor(x);
    }

main();
html, body, div {
    width:  100%;
    height: 100%;
    margin: 0;
  }
<body>
    <div id="design">
        <canvas id="flower"></canvas>
    </div>
</body>

为了达到预期的结果,使用下面的选项使用 isPointInPath 方法来检测 canvas 形状

的点击
  1. 使用Path2D构造函数画圆

    const circle = new Path2D(); circle.arc(cx, cy, r, 0, 2 * Math.PI); ctx.fillStyle = color; ctx.fill(circle);

  2. 使用下面的点击事件监听器

canvas.addEventListener("click", function(event) { if (ctx.isPointInPath(circle, event.clientX, event.clientY)) { alert("you are inside the circle"); } });

有关 https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath

的更多详细信息,请参阅此 link

示例工作代码供参考

const canvas = document.getElementById("flower");
const ctx = canvas.getContext("2d");
var offsetX = canvas.offsetLeft;
var offsetY = canvas.offsetTop;
var circles = [];

function main() {
  if (typeof document !== "undefined") {
    var r = 20;
    for (var j = 0; j < 5; j++) {
      var cx = random() * canvas.width;
      var cy = random() * canvas.height;
      var r = 25;
      var color =
        "rgb(" +
        Math.floor(random() * 256) +
        "," +
        Math.floor(random() * 256) +
        "," +
        Math.floor(random() * 256) +
        ")";
      const circle = new Path2D();
      circle.arc(cx, cy, r, 0, 2 * Math.PI);
      ctx.fillStyle = color;
      ctx.fill(circle);
      canvas.addEventListener("click", function(event) {
        if (ctx.isPointInPath(circle, event.clientX, event.clientY)) {
          alert("you are inside the circle");
        }
      });
    }
  }
}

var seed = 1;
function random() {
  var x = Math.sin(seed++) * 10000;
  return x - Math.floor(x);
}

main();
html, body, div {
    width:  100%;
    height: 100%;
    margin: 0;
  }
<body>
    <div id="design">
        <canvas id="flower"></canvas>
    </div>
</body>

Codepen - https://codepen.io/nagasai/pen/NWWNmdj