den*_*iss 4 javascript actionscript-3
我正在尝试学习JavaScript,我想知道JavaScript是否像ActionScript的ENTER_FRAME一样有一个事件监听器.基本上,我希望这个事件监听器"一直"监听,而不仅仅是等待事件的任何特定实例(鼠标点击,键盘事件).
你在找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.
Run Code Online (Sandbox Code Playgroud)
实际上,setInterval也是在Flash中 - flash.utils.setInterval.
作为旁注 - 不幸的是,setInterval(在Flash和JS中)都可以对抗本机刷新率.在Flash中,ENTER_FRAME避免了这种情况 - 你在swf重新渲染时渲染.在浏览器中,好吧,setInterval根本无法做到这一点.
小智 5
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>
Run Code Online (Sandbox Code Playgroud)
感谢Keith Peters帮助解决了这一问题。强烈推荐他的书“ FriendsOfEd的书“ HTML5动画与Javascript”:http: //www.apress.com/9781430236658
| 归档时间: |
|
| 查看次数: |
13459 次 |
| 最近记录: |