js模拟抛物运动和惯性运动

js模拟抛物运动和惯性运动

一.普通移动

利用请求动画帧requesrannamitionframe()----16.67ms执行一次

1.布局

<body>
    <div class="wrap">
       <div class="ball"></div>
</div>
    
</body>

2.CSS样式

 <style>
        .wrap{
            width: 1200px;
            height: 600px;
            background-color: aqua;
            margin: 50px auto;
            position: relative;
        }
        .ball{
            width: 100px;
            height: 100px;
            background-color: red;
/* 设置圆角*/
            border-radius: 50%;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>

3.js实现(递归函数实现)

 <script>
        var spX = 3;
        var spY = 3;
        var oB = document.querySelector(".ball");
        var oW = document.querySelector(".wrap");
requestAnimationFrame(function moveBall (){
                  oB.style.left = oB.offsetLeft+spX+"px";
                    oB.style.top =oB.offsetTop+spY+"px";
requestAnimationFrame(moveball);//递归函数持续进行
}

二.在固定范围内运动

*大于最大值就把当前最大值给他并且速度取反

requestAnimationFrame(function moveBall (){
                    var wL = oB.offsetLeft + spX;
                    var wT = oB.offsetTop + spY;
//右
                    if(wL>=oW.offsetWidth-oB.offsetWidth){
                        wL = oW.offsetWidth-oB.offsetWidth;
                        spX = -spX;
                    }
//左
                    if(wL<=0){
                        wL = 0;
                        spX = -spX;
                    }
//下
                    if(wT>=oW.offsetHeight-oB.offsetHeight){
                        wT = oW.offsetHeight-oB.offsetHeight;
                        spY = -spY;
                    }
//上
                    if(wT<=0){
                        wT &#
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值