Skip to main content

拖放多个形状

说明: 拖放形状或通过双击或双击来移除它们。

import Konva from 'konva';

const width = window.innerWidth;
const height = window.innerHeight;

const stage = new Konva.Stage({
  container: 'container',
  width: width,
  height: height,
});

const layer = new Konva.Layer();

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];

for (let i = 0; i < 6; i++) {
  const box = new Konva.Rect({
    x: i * 30 + 50,
    y: i * 18 + 40,
    fill: colors[i],
    stroke: 'black',
    strokeWidth: 4,
    draggable: true,
    width: 100,
    height: 50,
  });

  box.on('dragstart', function () {
    this.moveToTop();
  });

  box.on('dragmove', function () {
    document.body.style.cursor = 'pointer';
  });
  
  // 双击移除盒子(桌面应用程序)
  // 和双击移除盒子(移动应用程序)
  box.on('dblclick dbltap', function () {
    this.destroy();
  });

  box.on('mouseover', function () {
    document.body.style.cursor = 'pointer';
  });
  
  box.on('mouseout', function () {
    document.body.style.cursor = 'default';
  });

  layer.add(box);
}

// 将图层添加到舞台
stage.add(layer);