一. 圆周运动 1.1 思路分析:
圆的方程为:
// (x0, y0)为圆心位置;(x, y)为圆上的点 (x - x0) ^ 2 + (y - y0) ^ 2 = r ^ 2 cos(angle) ^ 2 + sin(angle) ^ 2 = 1因此,综合以上两式,可得:
因此,应用正弦函数计算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因此,综合以上两式,可得:
由此可得出椭圆运动的坐标值。
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); })(); }演示如下:
本文作者:子匠_Zijor,转载请注明出处: