【问题标题】:Kineticjs remove multiple shapesKineticjs 删除多个形状
【发布时间】:2013-03-07 02:19:12
【问题描述】:

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

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);
}

【问题讨论】:

    标签: kineticjs


    【解决方案1】:

    为了能够一次删除每个矩形,我首先将新图层移动到 for 循环内。我还添加了一个组,每个矩形都添加到其中。然后在 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);
    }
    

    【讨论】:

    • 是的,真正的罪魁祸首是使用 this.remove() 而不是 rect.remove(),干得好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 2012-06-06
    • 2012-11-25
    • 2014-02-14
    • 2013-01-31
    相关资源
    最近更新 更多