JavaScript's version of ActionScript's Event.ENTER_FRAME event?

前端 未结 5 1444
别那么骄傲
别那么骄傲 2021-01-03 05:42

I am trying to learn JavaScript and I am wondering whether JavaScript has a event listener just like ActionScript\'s ENTER_FRAME. Basically, I want this event listener to li

相关标签:
5条回答
  • 2021-01-03 05:58

    HTML5 provides access to the requestAnimationFrame()

    <canvas id="canvas" width="400" height="400"></canvas>
    <script>
    window.onload = function () {
        var canvas = document.getElementById('canvas'),
        context = canvas.getContext('2d'),
    
        var counter = 0;
    
        (function drawFrame () {
            window.requestAnimationFrame(drawFrame, canvas);
            context.clearRect(0, 0, canvas.width, canvas.height);
            console.log(counter++);
            // animation code goes here
        }());
    };
    </script>
    

    Credit goes to Keith Peters for helping sort this out. Highly recommend his book 'HTML5 animation with Javascript' by FriendsOfEd: http://www.apress.com/9781430236658

    0 讨论(0)
  • 2021-01-03 05:59

    Nope. Not really. A good substitute would be setInterval or setTimeout:

    function doAllTheTime() { }
    function wrapper() {
        doAllTheTime();
        setTimeout(wrapper, 40);
    }
    wrapper();
    

    But even then, you're pretty limited, because you don't have access to any of the event object properties.

    0 讨论(0)
  • 2021-01-03 06:05

    This would probably be worth a look too : http://paulirish.com/2011/requestanimationframe-for-smart-animating/

    0 讨论(0)
  • 2021-01-03 06:07

    I am still learning how to convert AS3 to JavaScript, but would it not be this function:

    createjs.Ticker.addEventListener("tick", gameLoop);
    

    gameLoop is the custom function that will be called on every 'tick'.

    Check out this helpful example of writing a game in Adobe Animate CC using JavaScript instead of AS3: https://software.intel.com/en-us/html5/hub/blogs/flash-cc-to-html5

    0 讨论(0)
  • 2021-01-03 06:16

    You're looking for setInterval(func, time). In the case of making it work like ENTER_FRAME, then you would make time very small. So, if you wanted to imitate a frame rate of say, 30 times a second:

     // you will need to make sure you have good scoping around the function param.
     setInterval(function(){console.log('enterframe')}, 33) 
     // 33 is about 1000 milliseconds / 30.
    

    Actually, setInterval is in Flash too -- flash.utils.setInterval.

    As a side note -- unfortunately, setInterval (in both Flash and JS) can work against the native refresh rate. In Flash ENTER_FRAME avoids this -- you render when the swf re-renders. In the browser, well, setInterval simply can't do that.

    0 讨论(0)
提交回复
热议问题