如何使html5动画流畅?

时间:2012-05-27 06:07:42

标签: html5

我正在为我的动画使用canvas和webkitrequestAnimation框架.. 然而,动画是即时的而不是平滑的..它是如此之快,我看不到任何动画.. 如何使动画流畅?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Wave 2</title>

</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>

<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
angle = 0,
range = 50,
centerY = canvas.height / 2,
xspeed = 1,
yspeed = 0.05,
xpos = 0,
ypos = centerY;
context.lineWidth = 2;
(function drawFrame () {
window.webkitrequestAnimationFrame(drawFrame, canvas);

context.beginPath();
context.moveTo(xpos, ypos);
//Calculate the new position.
xpos += xspeed;
angle += yspeed;
ypos = centerY + Math.sin(angle) * range;
context.lineTo(xpos, ypos);
context.stroke();
}());
};
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

除了第24行的语法错误之外,这对我有效:

window.webkitrequestAnimationFrame(drawFrame, canvas);

window.webkitRequestAnimationFrame(drawFrame, canvas);

在此页面上查看答案:How to use requestAnimationFrame

它将指导您编写一个请求动画功能,该功能适用​​于所有兼容的Web浏览器,而不仅仅是那些基于webkit的浏览器。如果您使用Safari或Chrome以外的浏览器,可能会解释任何不稳定的行为。

我想在这里提倡createjs.com,因为它们为处理HTML5画布和动画提供了很好的API。查看演示和源代码!

相关问题