原理揭示
圆周运动一定有个圆心(X,Y),只需要改变每个小球的 left 和 top 值来让小球运动。求小球在圆中的 x,y 必须借用三角函数,图中两个公式:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圆周运动</title>
<style>
*{margin: 0; padding: 0;}
ul {
list-style: none;
position: relative;
margin: 100px auto;
width: 500px;
height: 500px;
background-color: #f6f6f6;
transition: all 0.5 ease 0s;
transform-style: preserve-3d;
}
ul li {
position: absolute;
width: 40px;
height: 40px;
border-radius: 50%;
}
ul li:nth-child(1){background-color: rgba(255,255,0,0.6);}
ul li:nth-child(2){background-color: rgba(255,0,255,0.6);}
ul li:nth-child(3){background-color: rgba(0,255,255,0.6);}
ul li:nth-child(4){background-color: rgba(0,255,0,0.6);}
ul li:nth-child(5){background-color: rgba(255,0,0,0.6);}
</style>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<script>
var lis = document.getElementsByTagName("li");
cirmove({
"cir" : [230,230,210], //圆心x,y半径r
"degree" : 0,
"obj" : lis[0],
"interval" : 10
});
cirmove({
"cir" : [230,230,210], //圆心x,y半径r
"degree" : 90,
"obj" : lis[1],
"interval" : 10
});
cirmove({
"cir" : [230,230,210], //圆心x,y半径r
"degree" : 270,
"obj" : lis[2],
"interval" : 10
});
cirmove({
"cir" : [230,230,210], //圆心x,y半径r
"degree" : 180,
"obj" : lis[3],
"interval" : 10
});
cirmove({
"cir" : [230,230,0], //圆心x,y半径r
"degree" : 0,
"obj" : lis[4],
});
function cirmove(argetJSON){
//圆心x,y半径r
var x = argetJSON.cir[0];
var y = argetJSON.cir[1];
var r = argetJSON.cir[2];
// 操作的 DOM 对象
var obj = argetJSON.obj;
// 小圆起始的角度
var deg = argetJSON.degree;
// 定时器的时间
var interval = argetJSON.interval;
// 定时器让小圆运动起来
setInterval(move,interval);
// 小球旋转
function move(){
deg += 1;
obj.style.left = x + r * Math.cos(degreeToRad(deg)) + "px";
obj.style.top = y - r * Math.sin(degreeToRad(deg)) + "px";
}
// 角度换算为弧度,JS中的所有角度均为弧度制,想用角度就得转换一下。
function degreeToRad(degree){
const c = 180;
return degree * Math.PI / c;
}
}
</script>
</body>
</html>

网友评论