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>
相关推荐
90后小陈老师25 分钟前
WebXR教学 07 项目5 贪吃蛇小游戏
前端·数码相机
一口一个橘子27 分钟前
[ctfshow web入门] web118
前端·web安全·网络安全
GanGuaGua43 分钟前
Vue3:脚手架
前端·javascript·css·vue.js·vue
鸡吃丸子2 小时前
常见的实时通信技术(轮询、sse、websocket、webhooks)
前端·websocket·状态模式
胡斌附体2 小时前
vue添加loading后修复页面渲染问题
前端·javascript·vue.js·渲染·v-if·异步加载
酷爱码3 小时前
css中的 vertical-align与line-height作用详解
前端·css
沐土Arvin3 小时前
深入理解 requestIdleCallback:浏览器空闲时段的性能优化利器
开发语言·前端·javascript·设计模式·html
专注VB编程开发20年3 小时前
VB.NET关于接口实现与简化设计的分析,封装其他类
java·前端·数据库
小妖6663 小时前
css 中 content: “\e6d0“ 怎么变成图标的?
前端·css
L耀早睡4 小时前
mapreduce打包运行
大数据·前端·spark·mapreduce