Konva.js: 动态绘制矩形并删除 - 完整指南
使用 Konva.js 动态绘制矩形并删除,并添加一个按钮事件将所有新增的矩形全部删除。
绘制逻辑
if (pos.x >= startX && pos.x < startX + width / 2) {
var drawRect = new Konva.Rect({
x: startX,
y: pos.y - height / 2,
width: pos.x - startX + width / 2,
height: height,
fill: 'white',
stroke: 'transparent'
});
this.layer.add(drawRect);
this.getPointData(drawRect);
}
else if (pos.x > endX - width / 2 && pos.x <= endX) {
var drawRect = new Konva.Rect({
x: pos.x - width / 2,
y: pos.y - height / 2,
width: endX - pos.x + width / 2,
height: height,
fill: 'white',
stroke: 'transparent'
});
this.layer.add(drawRect);
this.getPointData(drawRect);
}
else if (pos.y >= startY && pos.y <= startY + height / 2) {
var drawRect = new Konva.Rect({
x: pos.x - width / 2,
y: startY,
width: width,
height: pos.y - startY + height / 2,
fill: 'white',
stroke: 'transparent'
});
this.layer.add(drawRect);
this.getPointData(drawRect);
}
else if (pos.y > endY - height / 2 && pos.y <= endY) {
var drawRect = new Konva.Rect({
x: pos.x - width / 2,
y: pos.y - height / 2,
width: width,
height: endY - pos.y + height / 2,
fill: 'white',
stroke: 'transparent'
});
this.layer.add(drawRect);
this.getPointData(drawRect);
}
else {
var drawRect = new Konva.Rect({
x: pos.x - width / 2,
y: pos.y - height / 2,
width: width,
height: height,
fill: 'white',
stroke: 'transparent'
});
this.layer.add(drawRect);
this.getPointData(drawRect);
}
删除所有矩形
在按钮的点击事件中,使用以下代码来删除layer上的所有矩形元素:
// 删除所有矩形
this.layer.find('Rect').destroy();
// 删除其他元素
// this.layer.find('OtherElement').destroy();
this.layer.draw();
解释:
this.layer.find('Rect'):使用find方法查找 layer 中所有Rect类型元素,并返回一个包含所有矩形的数组。.destroy():调用destroy方法将所有找到的矩形从 layer 中删除。this.layer.draw():调用draw方法重新绘制 layer,确保删除的元素立即生效。
注意:
- 如果 layer 上还有其他类型的元素需要删除,只需将
Rect替换为相应的类型即可。 getPointData(drawRect)函数需要根据你的具体需求进行实现,例如获取矩形的坐标、尺寸等信息。
使用技巧
- 在绘制矩形之前,可以先使用
layer.getIntersection(pos)方法判断鼠标位置是否与其他元素相交,避免绘制重叠的矩形。 - 可以使用
Konva.Group对象来组织多个元素,方便管理和操作。 - 使用
Konva.Transformer对象可以实现对矩形的交互式缩放、旋转、移动等操作。
希望以上内容能帮助你更好地理解 Konva.js 的使用,并实现你的动态绘制需求。
原文地址: https://www.cveoy.top/t/topic/peYb 著作权归作者所有。请勿转载和采集!