0

So I have a for loop generating, placing and tweening 20 rectangles. However the code only destroys the last generated rectangle. Is there an (ideally simple) way to ensure that the .destroy() applies to every rectangle instead of the last one?

$("#combat").click(function() {

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

        var rect = new Konva.Rect({
            x: -500,
            y: stage.height()*Math.random(),
            width: 480,
            height: 20,
            fill: 'green',
            stroke: 'black',
            strokeWidth: 3
        });

        layer.add(rect);

        tween = new Konva.Tween({
            node: rect,
            duration: 1,
            x: 500,
            onFinish: function() {
                rect.destroy()
            }
        }).play();

    }

});
AlwaysNeedingHelp
  • 1,851
  • 3
  • 21
  • 29

2 Answers2

1
        var tween = new Konva.Tween({
            node: pentagon,
            duration: 1,
            x: 500,
            onFinish: function() {
                // this will be tween instance
                // this.node will be rectangle
                console.log(this.node);
            }
        }).play();
lavrton
  • 18,973
  • 4
  • 30
  • 63
0

You can use Group object for this:

EDIT:

$("#combat").click(function() {

    var rectGroup = new Konva.Group();

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

        var rect = new Konva.Rect({
            x: -500,
            y: stage.height()*Math.random(),
            width: 480,
            height: 20,
            fill: 'green',
            stroke: 'black',
            strokeWidth: 3
        });

        rectGroup.add(rect);        
        layer.add(rectGroup);

        tween = new Konva.Tween({
            node: rect,
            duration: 1,
            x: 500,
            onFinish: function() {
                rectGroup.destroy()
            }
        }).play();

    }

});
Andrey Etumyan
  • 1,394
  • 11
  • 17
  • Sadly this isn't working. Still only the last rectangle is destroyed. Could it be because we are redefining the variable 'tween' each loop which overwrites the onFinish function for the previous definition? – AlwaysNeedingHelp Jul 10 '15 at 19:30
  • Sorry, it was my mistake, the Group object should be initialized before the loop. Code updated. – Andrey Etumyan Jul 10 '15 at 19:45
  • This works (huge thanks!) but is there a way to ensure it destroys only the rectangle? This is what I ultimately need to do because I have in my tween "duration: 2+Math.random()*4", and from what I can tell the script destroys the entire group after the last's rectangle tween is finished. – AlwaysNeedingHelp Jul 10 '15 at 19:56
  • You can define a variable with number of tweens before the loop. And then by decrementing it get the last Tween and destory a whole group. See example: http://codepen.io/etumyan/pen/MwGXgx?editors=101 – Andrey Etumyan Jul 10 '15 at 21:10