Konva.js 绘制矩形并删除 - 使用 Konva 库在画布上动态添加和移除矩形
以下代码展示了如何在 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);
}
// 添加删除按钮
<button id='deleteRectButton'>删除矩形</button>
// 删除按钮事件
var deleteRectButton = document.getElementById('deleteRectButton');
deleteRectButton.addEventListener('click', function() {
// 删除所有的矩形
this.layer.find('Rect').destroy();
this.layer.draw();
}.bind(this));
解释:
- 代码逻辑: 代码根据鼠标位置动态绘制矩形,并将绘制的矩形添加到
layer上。 - 删除按钮: 代码添加了一个按钮元素,并为其绑定了点击事件。
- 事件处理: 点击删除按钮时,事件处理程序会使用
layer.find('Rect')找到所有矩形,并使用destroy()方法将其删除。最后调用layer.draw()重新绘制画布。 - 保留其他元素: 由于
destroy()方法只会删除Rect元素,其他元素将保留在layer上。
注意: 为了使用这个代码,您需要确保已正确引入 Konva.js 库,并且已创建了一个 Konva 画布和 layer 对象。
希望这个代码示例能帮助您在 Konva.js 中动态添加和移除矩形,并实现其他互动功能。
原文地址: https://www.cveoy.top/t/topic/peYa 著作权归作者所有。请勿转载和采集!