首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >原生JS实现各种运动之重心运动

原生JS实现各种运动之重心运动

作者头像
越陌度阡
发布于 2020-11-26 15:27:51
发布于 2020-11-26 15:27:51
1.7K0
举报

给大家分享一个用原生JS实现的重心运动,所谓重心运动即为一个元素在向下运动触底时呈一定角度的递减回弹,效果如下:

实现代码如下,欢迎大家复制粘贴及吐槽。

代码语言:javascript
复制
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现各种运动之重心运动</title>
    <style>
        #div1 {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
        }
    </style>
    <script>
        var iSpeedX = 10;
        var iSpeedY = 10;

        function startMove() {

            setInterval(function () {

                var oDiv = document.getElementById('div1');

                //将Y轴增加速度,实现重力运动
                iSpeedY += 10;

                var l = oDiv.offsetLeft + iSpeedX;
                var t = oDiv.offsetTop + iSpeedY;

                //当元素碰到底边时
                if (t >= document.documentElement.clientHeight - oDiv.offsetHeight) {
                    //速度递减
                    iSpeedY *= -0.8;
                    iSpeedX *= 0.8;
                    //误差强行赋值
                    t = document.documentElement.clientHeight - oDiv.offsetHeight;

                    //当元素碰到上边时
                } else if (t <= 0) {
                    //速度递减
                    iSpeedY *= -0.8;
                    iSpeedX *= 0.8;
                    //误差强行赋值
                    t = 0;
                };

                //当元素碰到右边时
                if (l >= document.documentElement.clientWidth - oDiv.offsetWidth) {
                    //速度递减
                    iSpeedX *= -0.8;
                    //误差强行赋值
                    l = document.documentElement.clientWidth - oDiv.offsetWidth;

                    //当元素碰到左边时
                } else if (l <= 0) {
                    //速度递减
                    iSpeedX *= -0.8;
                    //误差强行赋值
                    l = 0;
                };

                //当X轴的速度绝对值小于0时
                if (Math.abs(iSpeedX) < 1) {
                    //强行终止
                    iSpeedX = 0;
                };

                //当Y轴的速度绝对值小于0时
                if (Math.abs(iSpeedY) < 1) {
                    //强行终止
                    iSpeedY = 0;
                };

                oDiv.style.left = l + 'px';
                oDiv.style.top = t + 'px';

            }, 30);
        }
    </script>
</head>

<body>
    <input type="button" value="开始运动" onclick="startMove()" />
    <div id="div1">
    </div>
</body>

</html>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档