首先得感謝segmentfault的回答讓我理解了圓周運動,否則我怎么都不明白,我還查了一大堆的資料
好的,那就開始講講圓周運動吧,要做圓周運動,就要用到三角函數(shù)和角度轉(zhuǎn)弧度的知識。我們先把最基本代碼貼上
html代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圓周運動</title>
<script src="utils.js"></script>
<script src="circle.js"></script>
<link rel="stylesheet" href="circle.css">
</head>
<body>
<div id="red">
<div id="blue"></div>
</div>
</body>
</html>
css代碼
* {
margin: 0;
padding: 0;
}
#red {
position: relative;
margin: 200px auto;
width: 400px;
height: 400px;
background: red;
border-radius: 50%;
}
#blue {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background: blue;
border-radius: 50%;
}
這上面的代碼沒問題,對吧,就是布局而已。
那怎么解決呢。咱們先看圖,

circle1.png
圖中o是圓心,A是大圓上的點,a是角度,點A到圓心O的距離是半徑。
由圖和經(jīng)驗來講,我們只需算出每一度的x,y就可以了,我們都知道
sin(a) = y / r,
cos(a) = x / r,
弧度=圓周率π / 180 * 角度a
而Math.sin,cos中用的是弧度, 所以我們可以得出,
Math.sin(圓周率π / 180 * 角度a ) = x / 半徑r;
Math.cos(圓周率π / 180 * 角度a ) = y / 半徑r;
最后可以推導出
x = Math.sin(圓周率π / 180 * 角度a) * 半徑r;
y = Math.cos(圓周率π / 180 * 角度a) * 半徑r;
window.onload = function () {
let blue = $("blue");
//起始角度
let degree = 0;
setInterval(function () {
//每個50ms +1個角度
degree += 1;
//計算弧度
let rad = Math.PI / 180 * degree;
//計算大圓上每一個A的x,y
let x = Math.sin(rad) * 200;
let y = Math.cos(rad) * 200;
//
blue.style.left = x + "px";
blue.style.top = y + "px";
}, 50);
}
但是如果我們直接把x,y設(shè)置給小圓的x,y是不行的,原因是它默認是圍著原點(0,0)旋轉(zhuǎn),所以你要先指定圓心位置,那這個圓心位置又是多少呢。我布局中的紅色圓的width是400,那么圓心就是(200,200)嗎?當然不是了,(200,200)確實是紅色圓的圓心,但不是藍色圓圍著轉(zhuǎn)的圓的圓心,我們必須減去藍色圓的半徑,即圓心是(150,150)。因為元素定位的時候是按照元素左上角位置定位的,而不是元素的中心定位,所以呢要減去50。如圖

circle2.png
圖中A的位置是正中心,但是由于元素定位的時候是按照元素左上角位置定位的,所以點B的位置才是真正的圓心,故最后js代碼是 ↓↓↓↓↓
window.onload = function () {
let blue = $("blue");
//x,y表示大圓心坐標
let ox = 150;
let oy = 150;
//起始角度
let degree = 0;
setInterval(function () {
//每個50ms +1個角度
degree += 1;
//計算弧度
let rad = Math.PI / 180 * degree;
//計算大圓上每一個A的x,y
let x = Math.sin(rad) * 200;
let y = Math.cos(rad) * 200;
//
blue.style.left = ox + x + "px";
blue.style.top = oy + y + "px";
}, 50);
}