我正在学习JavaScript,想知道它是否有像ActionScript的ENTER_FRAME一样的事件监听器。基本上,我希望这个事件监听器可以“一直”监听,而不仅仅是等待任何特定实例(鼠标单击、键盘事件)的事件。
我正在学习JavaScript,想知道它是否有像ActionScript的ENTER_FRAME一样的事件监听器。基本上,我希望这个事件监听器可以“一直”监听,而不仅仅是等待任何特定实例(鼠标单击、键盘事件)的事件。
HTML5 提供了访问 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>
感谢Keith Peters帮助梳理了这个问题。强烈推荐他的书《HTML5动画与JavaScript》(FriendsOfEd出版): http://www.apress.com/9781430236658
您需要使用setInterval(func, time)
函数。如果想要让它像ENTER_FRAME一样工作,那么您需要将时间设定得非常小。例如,如果您想模拟每秒30帧的帧率:
// 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.
实际上,setInterval
在 Flash 中也存在 -- flash.utils.setInterval
。
顺便说一句 -- 不幸的是,setInterval
(无论是在 Flash 还是 JS 中)可能会与本地刷新率相冲突。在 Flash 中,ENTER_FRAME 可以避免这种情况 -- 当 swf 重新渲染时进行渲染。在浏览器中,setInterval
简单地无法做到这一点。
createjs.Ticker.addEventListener("tick", gameLoop);
gameLoop
是每个“tick”时都会被调用的自定义函数。
请查看以下有用的示例,在Adobe Animate CC中使用JavaScript编写游戏而不是AS3:https://software.intel.com/en-us/html5/hub/blogs/flash-cc-to-html5
不是真的。一个很好的替代品是setInterval
或setTimeout
:
function doAllTheTime() { }
function wrapper() {
doAllTheTime();
setTimeout(wrapper, 40);
}
wrapper();
但即使如此,你的能力仍然受到限制,因为你无法访问任何事件对象属性。