小案例--圆点沿圆的路径无限运动,用到了定时器、动画

一、圆周运动(CSS实现)

<style>
        #wrap{
            position: relative;
            width: 500px;
            height: 500px;
            margin:100px auto;
            border:1px solid;
            border-radius: 50%;
        }
        #wrap p{   
            position: absolute;
            top: 235px;   /*此处的数值是测试来的*/
            left: 0;
            height: 0;
            width: 100%;
            transform: rotate(90deg);
            animation: goudan 5s linear infinite;
        }
        #wrap span{
            position: absolute;
            left: -5px;
            top: -5px;
            width: 10px;
            height: 10px;
            background-color: rgb(54, 10, 250);
            border-radius: 50%;
        }
        @keyframes goudan{
            from{
                transform: rotate(90deg);
            }
            to{
                transform: rotate(450deg);
            }
        }
    <!--  构造一个大圆,并且使得一个小圆点在大圆的线上无限运动 -->
    <div id="wrap">
        <!-- 此处的p,相当于一个棍,顶部是span-小圆点,棍的宽度与圆的宽度相同,且运动,中点与圆点重合 -->
        <p><span></span></p>
    </div>

二、圆周运动(js实现)

 <div id="wrap"> 
        <p class="ball"></p>
 </div>
 <script>
      (function(){
           let oBall = document.querySelector("#wrap .ball")
           let rad = 0    // rad表示角度值,初始不赋值的话,属性为undefined,并入运算不对

            // setInterval(function(){    // 用这个方法,运动会卡,用requestAnimationFrame
                // rad += 0.01
                // let left = Math.sin(rad)*250+250
                // let top = 250-Math.cos(rad)*250
                // oBall.style.left = left+"px"
                // oBall.style.top = top+"px"
            // },1000/60)

            let timer
            requestAnimationFrame(function move(){
                rad += 0.05
                let left = Math.sin(rad)*250+250
                let top = 250-Math.cos(rad)*250
                oBall.style.left = left+"px"
                oBall.style.top = top+"px"
                timer = requestAnimationFrame(move)
            })
            document.onclick = function(){
                cancelAnimationFrame(timer)
            }
        })()      
    </script>
<style>
        #wrap{
            width: 500px;
            height: 500px;
            border: 1px solid blue;
            margin: 100px auto;
            border-radius: 50%;
            position: relative;
        }
        #wrap p.ball{
            position: absolute;
            top: 0;
            left: 250px;
            width: 20px;
            height: 20px;
            margin-top: -10px;
            margin-left: -15px;
            background-color: rgb(29, 233, 29);
            border-radius: 50%;
        }
    </style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值