0
votes

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

    }

});
2

2 Answers

1
votes
        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();
0
votes

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

    }

});