Javascript 循环选择所有矩形
Javascript loop selects all rectangles
每当我单击画布上的单个矩形时,它都会清除所有矩形。如何仅清除我在画布上单击的矩形?我想问题出在我的代码中的 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
}
}
相关文章:
- 按照选项卡索引的顺序循环一个jQuery选择
- 如何在php中的jquery中对循环内的选择框值求和
- 当选择值x时,Javascript需要在正确的位置显示文本区域,从而循环通过具有选择选项的表单
- 用于使用javascript循环选择选项
- 循环遍历元素jquery选择器
- 循环选择标记并创建数组或字符串
- 在 while 循环中选择与整数值对应的数组
- 使用循环填充选择
- 使用 for 循环用逗号分隔的值填充选择元素
- 如何在每个循环中选择空输入
- javascript循环选择特定项目
- jquery:如何循环选择多个项目
- Javascript 循环选择所有矩形
- Jquery 使用键向上和向下键循环选择列表项
- jQuery循环选择的最佳方法
- 在Javascript中使用循环选择id的数量
- 通过循环选择复选框
- For循环选择特定的id并更改它们的样式- js
- 为什么我的Javascript循环返回时未定义?如何使用为循环选择对象
- jQuery循环选择并设置所选选项