我正在尝试创建一个简单的画布动画,其中一个小球绕着更大的球运行。我正在使用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)制作混合移动游戏。画布,但如果Javascript的性能如此糟糕,我不妨马上忘记它。
顺便说一下: 动画运行相当不错(大部分时间)与笔记本电脑但三星Galaxy A标签requestAnimationFrame给我这样(60fps,60fps,60fps,29fps,29fps,60fps,60fps,60fps,29fps .....)
答案 0 :(得分:0)
滞后很难注意到,但它存在。我调整了你的代码,使滞后更加明显。
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>