一. 圆周运动
1.1 思路分析:
圆的方程为:
// (x0, y0)为圆心位置;(x, y)为圆上的点
(x - x0) ^ 2 + (y - y0) ^ 2 = r ^ 2
cos(angle) ^ 2 + sin(angle) ^ 2 = 1
因此,综合以上两式,可得:
x = r * cos(angle) + x0
y = r * sin(angle) + y0
因此,应用正弦函数计算y坐标,用余弦函数计算x坐标。
1.2 实例:
// cancelRequestAnimFrame的兼容函数
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout;
} )();
window.onload = function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
ball = new Ball(2),
angle = 0,
centerX = canvas.width / 2,
centerY = canvas.height / 2,
radius = 50,
speed = 0.05,
timer = null;
ball.lineWidth = 0;
(function drawFrame() {
timer = window.requestAnimationFrame(drawFrame, canvas);
if(angle > Math.PI * 2 && timer) {
window.cancelRequestAnimFrame(timer);
timer = null;
}
// context.clearRect(0, 0, canvas.width, canvas.height);
ball.y = centerY + Math.sin(angle) * radius;
ball.x = centerX + Math.cos(angle) * radius;
angle += speed;
ball.draw(context);
})();
}
二. 椭圆运动
2.1 思路分析:
椭圆的方程为:
// (x0, y0)为椭圆的圆心位置;(x, y)为椭圆上的点
[(x - x0) / radiusX] ^ 2 + [(y - y0) / radiusY] ^ 2 = 1
cos(angle) ^ 2 + sin(angle) ^ 2 = 1
因此,综合以上两式,可得:
x = radiusX * cos(angle) + x0
y = radiusY * sin(angle) + y0
由此可得出椭圆运动的坐标值。
2.2 实例:
// cancelRequestAnimFrame的兼容函数
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout;
} )();
window.onload = function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
ball = new Ball(2),
angle = 0,
centerX = canvas.width / 2,
centerY = canvas.height / 2,
radiusX = 150,
radiusY = 100,
speed = 0.05,
timer = null;
ball.lineWidth = 0;
(function drawFrame() {
timer = window.requestAnimationFrame(drawFrame, canvas);
if(angle > Math.PI * 2 && timer) {
window.cancelRequestAnimFrame(timer);
timer = null;
}
// context.clearRect(0, 0, canvas.width, canvas.height);
ball.y = centerY + Math.sin(angle) * radiusY;
ball.x = centerX + Math.cos(angle) * radiusX;
angle += speed;
ball.draw(context);
})();
}