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>
相关推荐
IT_陈寒20 分钟前
Python的多线程就是个假把式,我算是体验到了
前端·人工智能·后端
OpenTiny社区1 小时前
【直播分享】GenUI SDK 技术公开课第二讲 | GenuiChat 核心配置深度解析
前端·github
计算机魔术师1 小时前
kernel.org 每天 600 万次请求,98% 不是人点的
前端
今日无bug1 小时前
从0到1手撕流式输出:Vue3 + Vite 实现 LLM 流式响应全解析
前端·vue.js·vite
光影少年1 小时前
react navite跨端项目的痛点、踩过哪些坑、怎么解决
前端·react native·react.js
默_笙2 小时前
🧀 用户访问一个网站到底经历了什么?全栈部署的"城市观光"指南
前端·javascript
aixingpan2 小时前
aixingpan.cn API开发文档:api_docs_trichart_natal_composite_transit2接口指南
前端·php
是立不是利2 小时前
CSS 架构——在混乱中建立秩序
前端·html
两只羊ovo2 小时前
让 Agent 接上“万能接口”:LangChain + MCP 实战,工具不再锁死在项目里
前端
妙码生花2 小时前
使用git更新ai-go-admin框架
前端·人工智能·git·golang·typescript·php