最新下载
热门教程
- 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);
})();
}
相关文章
- 王者荣耀侦探能力大测试攻略 王者荣耀侦探能力大测试怎么过 11-22
- 无期迷途主线前瞻兑换码是什么 11-22
- 原神欧洛伦怎么培养 11-22
- 炉石传说网易云音乐联动怎么玩 11-22
- 永劫无间手游确幸转盘怎么样 11-22
- 无期迷途主线前瞻兑换码是什么 无期迷途主线前瞻直播兑换码介绍 11-22