画布渲染性能

时间:2012-10-16 18:22:12

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

我正在修改Jump'n'Bump游戏的HTML5端口,以便在Apple和基于Android的移动设备上运行。我使用廉价的1 GHz Cortex-A8 Android 4.0.3平板电脑进行测试。我在系统的浏览器中遇到了奇怪的行为。我通常得到一个非常低的帧速率约1 FPS(每帧重新绘制整个屏幕,使用setTimeout ......)。但是,当我添加一个< div>它有一个位置:在< canvas>之前固定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>

1 个答案:

答案 0 :(得分:1)

这个问题太好奇了。

尝试使用Request Animation Frame而不是setInterval(没有magic 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);
            };
}

也许这有助于提高表现。