06- 定时器作业 圆周运动

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#square{
position: relative;
width: 300px;
height: 300px;
border: 5px solid black;
margin: 120px auto 0 auto;
background-color:pink;
/*border-radius: 50%;*/
}
#ball{
position: absolute;
left: 100px;
top: 0px;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: skyblue;
}
#next{
text-align: center;
line-height: 80px;
}
</style>
</head>
<body>
<div id="square">
<div id="ball"></div>
</div>
<div id="next">
<input type="button" id='btn1' value='run'>
<input type="button" id='btn2' value='stop'>
</div>

<script>
/*1.求出x,y(变值)
2.θ角度开始为0,后面通过函数循环
3.函数开始后,每一个x,y都在变化
*/
var oRun = document.getElementById('btn1');
var oStop = document.getElementById('btn2');
var oSquare = document.getElementById('square')
var aBall = document.getElementById('ball')
var r = oSquare.clientWidth/2; //获取半径
var angle =0; //小球旋转的角度
var timer =0;//储存定时器的索引 可以不赋值
oRun.onclick = function(){
//清除掉上次的定时器
clearInterval(timer);
timer = setInterval(function(){
angle++; //0变成1再乘除,小球旋转的角度变大
//Math.sin( angle*Math.PI/180 ) = y/r
//Math.cos( angle*Math.PI/180 ) = x/r

// 算出圆周上每一个 A 的 x,y 轴
var x = Math.cos( angle*Math.PI/180 ) * r;
var y = Math.sin( angle*Math.PI/180 ) * r;
// 算出距离父级点的top和left
/* aBall.style.left = r + x + "px";
aBall.style.top = r-10 - y + "px";
这样有个问题,left和top的值不是到球心,而是到正方形的边
所以需要减去小球的半径
*/
aBall.style.left = r-10 + x + "px";
aBall.style.top = r-10 - y + "px";
},10)
}
oStop.onclick = function(){
clearInterval(timer)
}
</script>

</body>
</html>
posted @ 2019-07-05 17:11  小小oRa  阅读(168)  评论(0)    收藏  举报