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>
相关推荐
泯泷10 分钟前
「译」解析 JavaScript 中的循环依赖
前端·javascript·架构
抹茶san13 分钟前
前端实战:从 0 开始搭建 pnpm 单一仓库(1)
前端·架构
Senar41 分钟前
Web端选择本地文件的几种方式
前端·javascript·html
烛阴1 小时前
UV Coordinates & Uniforms -- OpenGL UV坐标和Uniform变量
前端·webgl
姑苏洛言1 小时前
扫码小程序实现仓库进销存管理中遇到的问题 setStorageSync 存储大小限制错误解决方案
前端·后端
烛阴1 小时前
JavaScript 的 8 大“阴间陷阱”,你绝对踩过!99% 程序员崩溃瞬间
前端·javascript·面试
lh_12542 小时前
ECharts 地图开发入门
前端·javascript·echarts
jjw_zyfx2 小时前
成熟的前端vue vite websocket,Django后端实现方案包含主动断开websocket连接的实现
前端·vue.js·websocket
Mikey_n2 小时前
前台调用接口的方式及速率对比
前端
周之鸥2 小时前
使用 Electron 打包可执行文件和资源:完整实战教程
前端·javascript·electron