我正在尝试创建一个简单的画布动画,其中一个小球绕着大球旋转。我正在使用requestAnimationFrame,但是我却无法正常工作。换句话说,我的动画有时运行得很慢(跟不上60fps)。我做了jsFiddle以获得更多视觉上的解释。

这也是我正在使用的javascript:

var layer1 = document.getElementById('layer1').getContext('2d');
var layer2 = document.getElementById('layer2').getContext('2d');

var x;
var y;
var angle = 0;

var last_frame = 0;

function render(timestamp) {

  requestAnimationFrame(render);

  fps = timestamp - last_frame;
  last_frame = timestamp;

  // optimal framerate would be 60 (~16ms/"loop") -> count ratio according to that
  // for example if fps is 32 -> 32/16 = 2 -> we move ball twice the normal distance
  var delta = fps / 16;

  angle += 0.02 * delta;

  x = 200 + 100 * Math.cos(angle);
  y = 200 + 100 * Math.sin(angle);

  layer1.clearRect(0, 0, 400, 400);

  layer1.beginPath();
  layer1.arc(x, y, 20, 0, Math.PI * 2);
  layer1.fill();

}
render(16);

layer2.beginPath();
layer2.arc(200, 200, 80, 0, Math.PI * 2);
layer2.fill();


我的代码有问题吗?我正在尝试使用Cordova(PhoneGap)和canvas制作混合手机游戏,但是如果Javascript的性能如此差,我不妨马上忘记它。

顺便说说:
动画在笔记本电脑上运行得很好(大部分时间),但在三星Galaxy上运行A选项卡requestAnimationFrame给我这样的效果(60fps,60fps,60fps,29fps,29fps,60fps,60fps,60fps,29fps ...

最佳答案

滞后很难察觉,但确实存在。我调整了您的代码以使滞后更加明显。



var layer1 = document.getElementById('layer1').getContext('2d');
var layer2 = document.getElementById('layer2').getContext('2d');

var x;
var y;
var angle = 0;
var last_frame = 0;
layer1.globalAlpha = .5;

function render(timestamp) {

  fps = timestamp - last_frame;
  last_frame = timestamp;

  // optimal framerate would be 60 (~16ms/"loop") -> count ratio according to that
  // for example if fps is 32 -> 32/16 = 2 -> we move ball twice the normal distance
  var delta = fps / 16;

  if (angle > Math.PI * 2) {
    layer1.clearRect(0, 0, 400, 400);
    angle %= Math.PI * 2;
  }

  angle += 0.02 * delta;
  x = 200 + 100 * Math.cos(angle);
  y = 200 + 100 * Math.sin(angle);

  layer1.beginPath();
  layer1.arc(x, y, 20, 0, Math.PI * 2);
  layer1.stroke();
  requestAnimationFrame(render);
}
render(16);
layer2.beginPath();
layer2.arc(200, 200, 80, 0, Math.PI * 2);
layer2.fill();

canvas,
#frames_label {
  position: absolute;
  top: 0;
  left: 0;
}

<canvas id="layer1" width="400" height="400">
</canvas>
<canvas id="layer2" width="400" height="400">
</canvas>
<div id="frames_label"></div>

08-18 00:46