【问题标题】:Canvas rendering performance画布渲染性能
【发布时间】:2012-10-06 22:13:20
【问题描述】:

我正在修改 Jump'n'Bump 游戏的 HTML5 端口,以便在基于 Apple 和 Android 的移动设备上运行。我使用便宜的 1 GHz Cortex-A8 Android 4.0.3 平板电脑进行测试。我在系统的浏览器中遇到了奇怪的行为。我通常会得到大约 1 FPS 的非常低的帧速率(每帧都重新绘制整个屏幕,使用 setTimeout ......)。但是,当我在 标记之前添加一个具有 position:fixed CSS 属性的

时,帧率会飞涨,游戏变得可玩了。

有人能解释一下这个奇怪的现象吗? Android 浏览器中是否存在一些影响画布性能的渲染模式?这是一个跨平台的问题吗?如何确保页面在用户浏览器中高效运行?

我正在编写的代码大纲:

<!DOCTYPE html>
<html>
<title>Jump'n'Bump - HTML5</title>
<meta http-Equiv="Cache-Control" Content="no-cache">
<meta http-Equiv="Pragma" Content="no-cache">
<meta http-Equiv="Expires" Content="0">
<meta name="viewport" content = "width=400px, user-scaleable=no">

<!-- javascript files included here -->
<script type="text/javascript" src="main.js"></script>

<style type="text/css">
  body { margin: 0px 0px 0xp 0px }
  canvas { border: 0px solid black; }
  img.resource { display:none; }
  #fixed_div { position: fixed; width: 10px; height: 10px; left: 0px; top: 0px; }
  #gameArea { position: absolute; left: 0px; top: 0px; width: 400px; height: 256px; background: red; }
  canvas {
    image-rendering: optimizeSpeed;             // Older versions of FF
    image-rendering: -moz-crisp-edges;          // FF 6.0+
    image-rendering: -webkit-optimize-contrast; // Webkit
    image-rendering: optimize-contrast;         // Possible future browsers.
    -ms-interpolation-mode: nearest-neighbor;   // IE
  }  
</style>
<body onload="init()" text="#FFFFFF" bgcolor="#000000">

<!-- image resources like this here: -->
<img class="resource" id='rabbits' src='rabbit.png'/>

<!-- *** remove the line below and the game slows down *** -->
<div id='fixed_div'></div>

<div id="gameArea"><canvas id="screen" width="400" height="256"></canvas></div> 

</body>
</html>

【问题讨论】:

  • 请问你用的是什么游戏引擎?
  • Jump'n'Bump,最初在 DOS 中运行。 HTML5 端口在此处可用:link。请参阅link 上的维基百科文章以获取其他端口的链接。
  • 它似乎没有使用任何游戏引擎。有一个函数用 setTimeout 来调度自己,并调用一个渲染函数,直接在画布上绘制。
  • 这很有趣,我在 Windows Phone 7 上得到了一个劣质的 FPS - 收藏这篇文章!

标签: performance html canvas android-browser frame-rate


【解决方案1】:

这个问题太奇怪了。

尝试使用请求动画帧而不是 setInterval(没有神奇的 div,=])

function getRequestAnimFrame() {
    var game = this;
    // requestAnim shim layer by Paul Irish
    return  window.requestAnimationFrame       || 
            window.webkitRequestAnimationFrame || 
            window.mozRequestAnimationFrame    || 
            window.oRequestAnimationFrame      || 
            window.msRequestAnimationFrame     || 
            function(/* function */ callback, /* DOMElement */ element) {
                window.setTimeout(callback, 1000 / fps);
            };
}

也许这有助于提高性能。

【讨论】:

  • 正确,但据我所知,大多数移动浏览器都不支持请求动画帧 - 请参阅link。据我所知,这可能是触发画布到屏幕更新而不是渲染到画布本身的问题。不过,感谢您的提示 - sn-p 在还针对桌面浏览器时非常有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多