canvas中的三角運動(5) —— 圓周運動和橢圓運動
一. 圓周運動
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);
})();
}</code></pre>
演示如下: http://codepen.io/dengzhirong/pen/akxQbx
二. 橢圓運動
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);
})();
}</code></pre>
演示如下: http://codepen.io/dengzhirong/pen/WxWYvX
來自:http://www.dengzhr.com/js/962