Kineticjs删除多个形状

时间:2013-03-07 02:19:12

标签: kineticjs

我添加了10个可拖动的矩形,我希望能够在逐个点击它们时删除它们。现在只删除第一个,然后它不再删除。是否可以在矩形ID中添加click事件?

http://jsfiddle.net/dmYbA/

var stage = new Kinetic.Stage({
    container: 'container',
    width: 578,
    height: 400
  });

  var layer = new Kinetic.Layer();

for (var i = 0; i< 10; i++) {

  var rect = new Kinetic.Rect({
    x: 239 + (i *3),
    y: 75 + (i * 3),
    width: 100,
    height: 50,
    fill: 'blue',
    stroke: 'black',
    strokeWidth: 4,
      draggable: true,
      id: i
  });

rect.on('click', function() {
   rect.hide();

});

  // add the shape to the layer
  layer.add(rect);

  // add the layer to the stage
  stage.add(layer);
}

1 个答案:

答案 0 :(得分:1)

为了能够一次删除每个矩形,我首先在for循环中移动了新图层。我还添加了一个添加了每个rect的组。然后在rect.on里面将它设置为this.remove()而不是rect.remove()。

http://jsfiddle.net/DP53S/

var stage = new Kinetic.Stage({
    container: 'container',
    width: 578,
    height: 400
  });



for (var i = 0; i< 10; i++) {
   var group = new Kinetic.Group({
    draggable: true
});
  var layer = new Kinetic.Layer();
  var rect = new Kinetic.Rect({
    x: 239 + (i *3),
    y: 75 + (i * 3),
    width: 100,
    height: 50,
    fill: 'blue',
    stroke: 'black',
    strokeWidth: 4
  });

rect.on('click', function() {
   this.remove();
   layer.draw();

});

  // add the shape to the layer
  group.add(rect)
  layer.add(group);

  // add the layer to the stage
  stage.add(layer);
}