JavaScript's version of ActionScript's Event.ENTER_FRAME event?
I am trying to learn JavaScript and I am开发者_如何学Python wondering whether JavaScript has a event listener just like ActionScript's ENTER_FRAME. Basically, I want this event listener to listen "all the time" not just wait for any particular instance (mouse click, keyboard event) of event.
This would probably be worth a look too : http://paulirish.com/2011/requestanimationframe-for-smart-animating/
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.
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
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
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.
精彩评论