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>
相关推荐
共享家952720 小时前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Halo_tjn1 天前
基于封装的专项 知识点
java·前端·python·算法
m0_748229991 天前
Vue2 vs Vue3:核心差异全解析
前端·javascript·vue.js
C澒1 天前
前端监控系统的最佳实践
前端·安全·运维开发
xiaoxue..1 天前
React 手写实现的 KeepAlive 组件
前端·javascript·react.js·面试
hhy_smile1 天前
Class in Python
java·前端·python
小邓吖1 天前
自己做了一个工具网站
前端·分布式·后端·中间件·架构·golang
南风知我意9571 天前
【前端面试2】基础面试(杂项)
前端·面试·职场和发展
LJianK11 天前
BUG: Uncaught Error: [DecimalError] Invalid argument: .0
前端
No Silver Bullet1 天前
Nginx 内存不足对Web 应用的影响分析
运维·前端·nginx