Search code examples
javascriptadobe-animate

Start Animation (Animate CC) only when the canvas become visible after scrolling.


I have an animation (made with Adobe animate CC) that I have included into my html file. I am trying to change its original script in order to start the animation from the beginning only when it becomes visible in the viewport of the browser. Unfortunately, I searched widely but couldn't make any of the solutions I found worked for my case.

This is the original code I'm trying to change:

<html>

<head>

<script>
var canvas, stage, exportRoot, anim_container, dom_overlay_container, 
fnStartAnimation;

function init() {
    canvas = document.getElementById("canvas");
    anim_container = document.getElementById("animation_container");
    dom_overlay_container = document.getElementById("dom_overlay_container");
    var comp=AdobeAn.getComposition("07578064E5C140B781D146A1AE4968A3");
    var lib=comp.getLibrary();
    handleComplete({},comp);
}
function handleComplete(evt,comp) {
    //This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
    var lib=comp.getLibrary();
    var ss=comp.getSpriteSheet();
    exportRoot = new lib.Water_illustrazione_revista_scrollplay();
    stage = new lib.Stage(canvas);  
    //Registers the "tick" event listener.
    fnStartAnimation = function() {
        stage.addChild(exportRoot);
        createjs.Ticker.setFPS(lib.properties.fps);
        createjs.Ticker.addEventListener("tick", stage);
    }

 //follow a code to support hidpi screens and responsive scaling.

</script>

</head>

<body onload="init();" style="margin:0px;">

<div id="anchor5" class="Anime_p">
 <div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:1280px; height:700px">
        <canvas id="canvas" width="1280" height="700" style="position: absolute; display: block; background-color:rgba(255, 255, 255, 1.00);"></canvas>
        <div id="dom_overlay_container" style="pointer-events:none; overflow:hidden; width:1280px; height:700px; position: absolute; left: 0px; top: 0px; display: block;">
        </div>
    </div>
</div>

</body>

</html>

Solution

  • You simply need to export the animation as stopped at first and then check when the div comes in browser view. Whenever it does, start the animation.

    1. Add exportRoot.stop(); in the end of fnStartAnimation();
    2. Check for visibility of your animation div in browser as explained here - How to tell if a DOM element is visible in the current viewport?
    3. Whenever the condition is satisfied, add the code - exportRoot.play();