Javascript循环选择所有矩形

Javascript循环选择所有矩形,javascript,canvas,Javascript,Canvas,每当我单击画布上的单个矩形时,它会清除所有矩形。如何仅清除在画布上单击的矩形?我想问题在于我的代码中的for循环,因为它在所有矩形中循环 for(var i = 0; i < rect.length; i++){ // Check if the x and y coordinates are inside the rectangle if(x > rect[i].x && x < rect[i].x + rect[i].width

每当我单击画布上的单个矩形时,它会清除所有矩形。如何仅清除在画布上单击的矩形?我想问题在于我的代码中的for循环,因为它在所有矩形中循环

for(var i = 0; i < rect.length; i++){
    // Check if the x and y coordinates are inside the rectangle
    if(x > rect[i].x && x < rect[i].x + rect[i].width
        && y > rect[i].y && y < rect[i].y + rect[i].height)
    {
        // If true, clear the rectangle
        for(var j = 0; j < rect.length; j++){
            ctx.clearRect(rect[j].x,rect[j].y,rect[j].width,rect[j].height);
        }
    }
}
for(变量i=0;irect[i].x&&xrect[i]。y&&y
如果我正确理解了您的代码,那么问题是您的第二个for循环。找到正确的矩形后,再次遍历所有矩形。试试这个:

for(var i = 0; i < rect.length; i++){
    // Check if the x and y coordinates are inside the rectangle
    if(x > rect[i].x && x < rect[i].x + rect[i].width
        && y > rect[i].y && y < rect[i].y + rect[i].height)
    {
        // If true, clear the rectangle
        ctx.clearRect(rect[i].x,rect[i].y,rect[i].width,rect[i].height);
        break; //break out of the for loop since the rect was found
    }
}
for(变量i=0;irect[i].x&&xrect[i]。y&&y
你的答案有效。但是,你能进一步解释一下吗?谢谢如果我想循环两次或更多次,然后打破它呢?在循环中添加一个变量,然后再添加一个if,那么如果它达到某个数字,那么是否会中断?您的思路是正确的。您遇到的问题是,在找到正确的矩形后,您再次在所有矩形上循环并清除它们。因为一旦输入if语句,就已经找到了正确的矩形,所以只需清除它。从什么时候开始?