javascript - JS怎么让绕着圆运动的物体,速度慢慢减小,最后停下来?

查看:116
本文介绍了javascript - JS怎么让绕着圆运动的物体,速度慢慢减小,最后停下来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .js-circle-wrap{
            position: absolute;
            top: 100px;
            left: 600px;
            width: 400px;height: 400px;
            border: 1px solid red;
            border-radius: 50%;
        }
        .circle{
            width: 50px;
            height: 50px;
            border-radius:50%;
            position: absolute;
            left: 0;top: 0;
            background-color: lightblue;
        }
    </style>
</head>

<body>
    <div class="js-circle-wrap">
        <div class="circle"></div>
    </div>
</body>
<script src="./jquery-3.1.0.js"></script>
<script>
let wrap = document.querySelector('.js-circle-wrap');
let origX = parseInt(window.getComputedStyle(wrap,null).width)/2;
let origY = parseInt(window.getComputedStyle(wrap,null).height)/2;
let r = origX;

let circle = document.querySelector('.circle');
let circleR = parseInt(window.getComputedStyle(circle,null).width)/2;
let x,y;
let ang = 0;
setInterval(function(){
    if (ang < 360){
        ang += 0.1;
    }else{
        ang = 360;
    }
    x = parseInt(origX + r*Math.cos(ang) - circleR);
    y = parseInt(origY + r*Math.sin(ang) -circleR);
    circle.style.left = x + "px";
    circle.style.top = y + "px";
},100);

</script>
</html>

解决方案

var speed = 0.1;//增加一个speed变量
setInterval(function(){
    speed = speed - 0.001;//让速度减小
    if (speed > 0){
        ang += speed;
    }else{
        clearInterval();//清除定时器
    }
    x = parseInt(origX + r*Math.cos(ang) - circleR);
    y = parseInt(origY + r*Math.sin(ang) -circleR);
    circle.style.left = x + "px";
    circle.style.top = y + "px";
},100);

这篇关于javascript - JS怎么让绕着圆运动的物体,速度慢慢减小,最后停下来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆