Search code examples
javascriptcreatejstweenjs

TweenJs - rotate rectangle on click runs only once


I am trying to create simple animation on "click" event in JavaScript library called TweenJs (part of CreateJs suite), but it seems that animation updates the display only the first time when I click on the rectangle. After animation is over for the first time, on every next click it seems that code is running, but the display stands still (or doesn't update). You can see in the console that it logs start and the end of animation.

Can someone please help me and explain what is the problem with my code, and also, in general is this the right approach to use stage.update() ?

Here is my code:

https://codepen.io/milan_d/pen/rNaJEKY?editors=1111

Thank you very much!


Solution

  • The issue is that once you rotate it, it is already rotated to the angle you specify in subsequent clicks.

    An easy solution is to just add a zero-duration to() call when you click it that resets it.

    createjs.Tween.get(square)
        .to({rotation:0}) // This one has no duration, so it is immediate
        .to({rotation:360},3000)
        .call(squareRotationComplete);
    

    Another option is to always rotate it based on the initial tween

    createjs.Tween.get(square)
        .to({rotation:square.rotation + 360},3000)
        .call(squareRotationComplete);
    

    Lastly, you could use the RelativePlugin. First install it, and then just use "+360" in your to() call.

    createjs.RelativePlugin.install(); // Run once
    createjs.Tween.get(square)
        .to({rotation:"+360"},3000) // Note the value.
        .call(squareRotationComplete);
    

    Cheers!