Javascript 循环选择所有矩形

Javascript loop selects all rectangles

本文关键字:循环 选择 Javascript      更新时间:2023-09-26

每当我单击画布上的单个矩形时,它都会清除所有矩形。如何仅清除我在画布上单击的矩形?我想问题出在我的代码中的 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 循环。找到正确的矩形后,您可以再次遍历它们。试试这个:

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