使用余弦函数获得x坐标的大小,正弦函数获得y坐标的大小。
牢记:动画编程,谈及x,即想到余弦,谈及y,即想到正弦。
这里创建一个圆周运动和一个椭圆运动。
文件名:circle.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(),
angle = 0,
centerX = canvas.width/2,
centerY = canvas.height/2,
radius = 80,
speed = 0.05;
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.cos(angle) * radius;
ball.y = centerY + Math.sin(angle) * radius;
angle += speed;
ball.draw(context);
}());
};
</script>
</body>
</html>
文件名:oval.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>椭圆运动</title>
</head>
<style type="text/css">
#canvas{background-color: #99cc33;}
</style>
<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(),
angle = 0,
centerX = canvas.width/2,
centerY = canvas.height/2,
radiusX = 120,
radiusY = 60,
speed = 0.05;
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.cos(angle) * radiusX;
ball.y = centerY + Math.sin(angle) * radiusY;
angle += speed;
ball.draw(context);
}());
};
</script>
</body>
</html>
参见《HTML5+Javascript动画基础》。