原生js如何做一个圆周运动,类似于地球朝着太阳转的效果

示意图:



效果图:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{
margin:0; 
padding:0;
list-style: none
}
#ball{
position:absolute;
left:295px;
top:95px;
width:10px;
height:10px;
border-radius:50%;
background-color:black;
}
#centerDiv{
position:absolute;
left:100px;
top:100px;
width:400px;
height:400px;
border-radius:50%;
background-color:red;
}

</style>
</head>
<body  style="height:1000px;">
<input id="btn" type="button" value="动起来" />
<div id="centerDiv">

</div>
<div id="ball">

</div>
</body>
</html>


<script type="text/javascript" src="tools/util.js"></script>
<script type="text/javascript">
window.onload = function(){
$("btn").onclick = function(){
//1、圆心点  (300,300)
//2、半径(200)r
//3、起始位置(300,100) initLeft,intiTop
//4、假定度数为 angle;
    //那么此时的:
//currLeft = 起始位置(initLeft)+r*sin(angle)
//currTop =  起始位置(initTop)+(r-r*cos(angle));

//起始位置
let initLeft = 300;
let initTop = 100;
//半径
let r = 200;
//起始度数(角度)
let angle =0;

let myTimer = setInterval(function(){
angle++;//增加度数
//1、改变left和top的值(javascript中的数据);
let currLeft= initLeft+r*Math.sin(angle/180*Math.PI);//角度要转成弧度
let currTop = initTop+(r-r*Math.cos(angle/180*Math.PI));//角度要转成弧度

//3、改变外观(UI)
$("ball").style.left = (currLeft-5)+"px";
$("ball").style.top = (currTop-5)+"px";
},20);
}
}

</script>


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值