Healthbar Damage with GreenSock

by Eli Marudi

HTML

<script src="https://code.createjs.com/createjs-2014.12.12.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.16.1/TweenMax.min.js"></script>
<canvas id="canvas" width=1400 height=200></canvas>
<div id="damage">apply random change</div>

CSS

canvas {
    border:1px solid red;
}
#damage {
    border:1px solid black;
    background:gray;
    padding:5px;
    width:200px;
    text-align:center;
    border-radius:2px;
    cursor:pointer;
}
#damage:hover {
    background:lightgray;
}

JavaScript

var healthBarMaxWidth = 1200;
var healthBarTargetWidth = 200;

function animateText(nr) {

    var toAnimate = text;

    // create new text if already running
    if (TweenMax.isTweening(text)) {
       return false;
    }

    // apply text and x position
    toAnimate.text = Math.round(nr);
    toAnimate.color = (toAnimate.text >= 0) ? '#00ff00' : '#ff0000';
    var bounds = toAnimate.getBounds();
    toAnimate.x = -bounds.width / 2 + healthBar.scaleX;

    var tl = new TimelineLite();
    tl
    .set(toAnimate,{y: text.originalY,visible:true,alpha:1})
    .to(toAnimate,2,{y: 50,ease: Power3.easeOut})
    //.to(toAnimate,2,{alpha:0,ease: Power2. easeIn},"-=2")
    .call(function (stage, t) {
        if (t._cloned == true) {
            console.log('remove cloned');
            stage.removeChild(t);
        }
    },[stage, toAnimate]);
    
    
    // tweens
    /*
    createjs.Tween.get(toAnimate)
        .to({
        y: text.originalY
    })
        .to({
        y: 50
    }, 2000, createjs.Ease.getPowOut(3))

    createjs.Tween.get(toAnimate)
        .wait(0)
        .to({
        visible: true,
        alpha: 1
    })
        .to({
        alpha: 0,
        visible: false
    }, 2000, createjs.Ease.getPowIn(2))
    // optional: remove text if cloned
    .call(function (stage, t) {
        if (t._cloned == true) {
            console.log('remove cloned');
            stage.removeChild(t);
        }
    }, [stage, toAnimate]);
*/
};

function animateBar(change) {

    healthBarTargetWidth += change;
    if (healthBarTargetWidth > healthBarMaxWidth) healthBarTargetWidth = healthBarMaxWidth;
    if (healthBarTargetWidth < 0) healthBarTargetWidth = 0;

    // greensock tweens
    TweenLite.to(
    healthBar,
    1, {
        scaleX: healthBarTargetWidth,
        onUpdate: function () {
            healthBarText.text = Math.round(this.scaleX) + ' / ' + healthBarMaxWidth;
        },
        onUpdateScope: healthBar
    });
};

var stage = new...