use*_*696 2 javascript html5 canvas game-loop
我有一些关于JavaScript循环的问题.
问题:
这是自己尝试的画布代码:
<!doctype html>
<html>
<head>
</head>
<body>
<canvas id="c" width="400" height="400"></canvas>
<script type="text/javascript">
var c = document.getElementById( 'c' );
ctx = c.getContext( '2d' );
var x = 100;
ctx.fillStyle= '#f00';
function loop()
{
ctx.fillRect( x, 100, 20, 20 );
++x;
}
setInterval( loop, 1 );
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Ray*_*nos 10
为什么JavaScript循环会冻结浏览器(在C++中不会发生)
JavaScript是单线程的.在javascript代码运行或竞争条件发生时,DOM的状态不能改变.这意味着没有绘图/回流.
为什么绘图速度慢,即使每1毫秒绘制一次,也是最简单的事情!
它不是以1毫秒运行,它以10毫秒运行,因为浏览器不允许你紧紧地循环.
解决方案是什么?闪光灯即将消亡,我们现在做什么?
使用requestAnimationFrame并以60 FPS运行游戏,为什么还需要更多?
使用(webkit)requestAnimationFrame的示例,它为我顺利运行.