gpt4 book ai didi

Javascript 游戏循环

转载 作者:太空宇宙 更新时间:2023-11-04 13:39:14 24 4
gpt4 key购买 nike

我有一些关于 JavaScript 循环的问题。

问题:

  • 为什么 JavaScript 循环会卡住浏览器
  • 为什么绘图速度很慢,即使它以每 1 毫秒绘制 1 次的速度运行,而且它正在绘制最简单的东西!
  • 解决方案是什么? Flash 快要死了,我们现在该怎么办?

这是您自己尝试的 Canvas 代码:

<!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>

最佳答案

Why does a JavaScript loop freeze the browser ( does not happen in C++ )

JavaScript 是单线程的。 DOM 的状态在 javascript 代码运行时不能改变,否则会出现竞争条件。这意味着没有绘图/回流。

Why is the drawing slow even do it's running at 1 draw every 1ms and it's drawing the simplest thing!

它不是以 1 毫秒运行,而是以 10 毫秒运行,因为浏览器不允许您如此紧密地循环。

What's the solution? flash is dying, what do we do now?

使用 requestAnimationFrame 并以 60 FPS 运行您的游戏,为什么您需要更多?

Example using (webkit) requestAnimationFrame这对我来说运行顺利。

关于Javascript 游戏循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8108598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com