如何识别在 canvas 上绘制的矩形上的点击

How to recognize a click on a drawn rectangle on canvas

假设我们在 html5 canvas:

中绘制了多个矩形
    context.fillStyle='black';
    context.fillStroke='black';
    context.beginPath();
for(var i=0; i<50; i++)
{  
    context.rect(i*20,i*20,w,h);
//this is just some random configuration for the rectangles, it doesn't really matter how they are positioned
}
    context.closePath();
    context.fill();
    context.stroke();

我怎样才能让它在用户点击一个单独的矩形然后改变它的颜色时被识别出来?

是否有可能或者我必须创建一个函数来获取鼠标的 x 和 y 坐标,然后检查它与矩形的 x 和 y 坐标相比着陆的位置,最终找到 "covers"鼠标坐标?

IMO 最好跟踪数组内的矩形并循环遍历它们以查看它是否在其中。

如所述Here:

When you draw to a canvas element, you are simply drawing a bitmap in immediate mode.

The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.[...]

但是:我找到了这个Alternative