最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
html5中canvas 圆周运动和椭圆运动例子
时间:2022-06-25 18:11:59 编辑:袖梨 来源:一聚教程网
一. 圆周运动
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.line;
(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.line;
(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);
})();
}
相关文章
- 分析师称柴犬币目标价为0.000032美元,或将开启更大规模反弹 07-08
- 斗罗大陆怎么获得换武魂转换卡 斗罗大陆获得换武魂转换卡方法推荐 07-08
- 三角洲行动长弓溪谷大金在哪 三角洲行动长弓溪谷大金位置大全 07-08
- 密安币(PAP币)不合法 07-08
- 二重螺旋武器怎么获取 武器锻造与切换技巧详解 07-08
- 炉石传说安戈洛萨满预构筑卡组推荐 07-08