每当我单击 Canvas 上的单个矩形时,它都会清除所有矩形。如何仅清除 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
&& 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
}
}
关于Javascript循环选择所有矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27878531/