将单个正弦波发展至两个正弦波,分别改变对象不同的属性,一个用于改变x轴坐标,一个用于改变y轴坐标,造成的结果像随机运动(其实可以预测轨迹)。文件名:random.html。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>随机运动</title>
<style type="text/css">
#canvas{background-color: #99cc33;}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script type="text/javascript" src="utils.js"></script>
<script type="text/javascript" src="ball.js"></script>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
ball = new Ball(),
angleX = 0,
angleY = 0,
range = 100,
centerX = canvas.width/2,
centerY = canvas.height/2,
xspeed = 0.08;
yspeed = 0.12;
ball.x = canvas.width/2;
ball.y = canvas.height/2;
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){
return window.setTimeout(callback,1000/60);
})
};
(function drawFrame(){
window.requestAnimationFrame(drawFrame,canvas);
context.clearRect(0,0,canvas.width,canvas.height);
ball.x = centerX + Math.sin(angleX) * range;
ball.y = centerY + Math.sin(angleY) * range;
angleX += xspeed;
angleY += yspeed;
ball.draw(context);
}());
};
</script>
</body>
</html>
效果图:
参见《HTML5+Javascript动画基础》。