Search code examples
tweenjs

Simple TweenJS : tweening a div


I'm trying to do something really simple with TweenJS, which after using GSAP I find less intuitive. Just want to tween a div - already set up to contain an image - with CSS/HTML:

<script type="text/javascript" src="https://code.createjs.com/easeljs-0.8.2.min.js"></script>
<script type="text/javascript" src="https://code.createjs.com/tweenjs-0.6.2.min.js"></script>

<script>

function init() {

        stage = new createjs.Stage("canvas1");

        var txt1 = document.getElementById("Div_txt1");  
        createjs.Tween.get(txt1).to({opacity: 0}, 1000);

}      

</script>    

<body onload="init();">
<canvas id="canvas1" width="300" height="250"></canvas>
</body>
</html>

But this doesn't work and throws no errors.


Solution

  • TweenJS doesn't really know how to tween properties of a DIV because they do not exist on the element directly, but on the CSS style object instead, and use string values (such as "2px") instead of numbers. You can install the TweenJS CSSPlugin, which makes a number of CSS properties become tweenable, including position, rotation, and opacity.

    <script src="https://rawgit.com/CreateJS/TweenJS/master/src/tweenjs/CSSPlugin.js"></script>
    
    // Sample code
    createjs.Tween.get(div).to({opacity: 0}, 1000);
    

    This plugin was created to show how plugins can work, so it is very simple, as a result, it only understands tweening properties directly on elements, not defined in CSS classes. This means you must add an inline style to make it work:

    <div id="div" style="opacity:1">Text</div>
    

    Here is a working fiddle: http://jsfiddle.net/xc3pt2b8/

    EDIT The updated CSSPlugin in TweenJS 1.0.0 will work with computed styles when the compute flag is turned on. Its less performant, but more powerful. https://createjs.com/docs/tweenjs/classes/CSSPlugin.html