使用 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();

解释:

  1. this.layer.find('Rect'):使用 find 方法查找 layer 中所有 Rect 类型元素,并返回一个包含所有矩形的数组。
  2. .destroy():调用 destroy 方法将所有找到的矩形从 layer 中删除。
  3. 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 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录