CSS+JQuery 实现弹力球效果,碰到屏幕边框弹回

实现弹力球效果,碰到屏幕边框弹回,效果如下

代码如下:

html 复制代码
<img src="../image/ball.png" alt="" class="ball">
<style>
    .ball {
        position: fixed;
        top: 50vh;
        left: 50vw;
        width: 15vw;
        height: 15vw;
        border-radius: 50%;
        z-index: 0;
    }
</style>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
    const ball = document.querySelector('.ball');
    let posX = window.innerWidth / 2;
    let posY = window.innerHeight / 2;
    let velX = 2;
    let velY = 2;
    const friction = 0.5;
    let rotation = 0;
    const rotationSpeed = 3;

    function moveBall() {
        posX += velX;
        posY += velY;

        // Bounce off the edges
        if (posX <= 0 || posX + ball.offsetWidth >= window.innerWidth) {
            velX = -velX * friction;
            posX = Math.min(Math.max(posX, 0), window.innerWidth - ball.offsetWidth);
        }

        if (posY <= 0 || posY + ball.offsetHeight >= window.innerHeight) {
            velY = -velY * friction;
            posY = Math.min(Math.max(posY, 0), window.innerHeight - ball.offsetHeight);
        }

        rotation += rotationSpeed;
        ball.style.left = posX + 'px';
        ball.style.top = posY + 'px';
        ball.style.transform = 'rotate(' + rotation + 'deg)';

        requestAnimationFrame(moveBall);
    }

    moveBall();
</script>
相关推荐
怕浪猫15 分钟前
第一章、Chrome DevTools Protocol (CDP) 详解
前端·javascript·chrome
kyriewen31 分钟前
从本地到生产:迁移到 GitHub Actions 自动化 CI/CD,总结了这 5 个坑
前端·github·自动化运维
雨季mo浅忆44 分钟前
首个Vue3项目边写边学边记
前端·vue3
IT_陈寒2 小时前
React中useEffect依赖项这个坑我居然踩了三天
前端·人工智能·后端
qq4356947012 小时前
Vue04
前端·vue.js
我是真菜3 小时前
彻底理解js中的深浅拷贝
前端·javascript
江畔柳前堤3 小时前
github实战指南07-CLI 与高级技巧
前端·人工智能·chrome·深度学习·github·caffe·issue
kisdiem4 小时前
ReAct:让大模型一边推理,一边行动
前端·react.js·前端框架
西部荒野子4 小时前
JS 如何跑进两个原生世界
前端
RANxy4 小时前
AntV 入门系列第一篇:从零开始的数据可视化之旅
前端