JS 的 Math.sin() 与 Math.cos() 用法(小球沿轨迹做运动)
功能实现后红色小球会沿着黑线做顺时针运动
上代码
<html>
<head>
<style type="text/css">
.warp {
position: relative;
width: 500px;
height: 120px;
border-radius: 60px;
margin: 200px auto;
border: 1px solid #999
}
.box {
width: 36px;
height: 36px;
position: absolute;
top: -18px;
left: 42px;
background-color: red;
border-radius: 50%;
}
</style>
<script type="text/javascript" src="./jquery.min.js"></script>
</head>
<body>
<div class="warp">
<div class="box"></div>
</div>
</body>
<script type="text/javascript">
/**
* 公式: Math.sin(x) 和 Math.cos(x) 其中 x 是弧度
弧度 = 角度 *(PI/180)
a,b是圆心坐标,即(a,b); r是圆半径;
一个圆为360°,一分钟为60秒,所以平均每秒的转动角度为 360°/60 = 6°,那么半圆的角度就是 3°
综上:X坐标(left) = a + Math.sin(3 * (Math.PI / 180)) * r
Y坐标(top) = b + Math.cos(3 * (Math.PI / 180)) * r
注意:此处的“+”或“-”号,是可以控制运动方向的,即是顺时针还是逆时针
**/
var r = 60; //半径 60-36/2=42 500-42-42=416
var n = 60; // 左半圆的圆心坐标为(42,42) 右半圆的圆形坐标为(416,42)
$(".box").animate({ left: 416, }, 3000, "linear", function () {
var move1 = function () {
$(".box").animate({
left: 416 + Math.sin(3 * (Math.PI / 180) * (n)) * r,
top: 42 + Math.cos(3 * (Math.PI / 180) * (n)) * r
}, 30, "linear", function () {
n--;
if (n < 1) {
n = 60
$(".box").animate({ left: 42, }, 3000, "linear", function () {
var move2 = function () {
$(".box").animate({
left: 42 - Math.sin(3 * (Math.PI / 180) * (n)) * r,
top: 42 - Math.cos(3 * (Math.PI / 180) * (n)) * r
}, 30, "linear", function () {
n--;
if (n < 1) {
n = 60
$(".box").animate({ left: 416, }, 3000, "linear", function () {
// move1();//回调函数
})
} else {
move2();//回调函数
}
});
}
move2();
});
} else {
move1();//回调函数
}
});
}
move1();
});
</script>
</html>