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>
相关推荐
郑州光合科技余经理14 分钟前
海外国际版同城服务系统开发:PHP技术栈
java·大数据·开发语言·前端·人工智能·架构·php
一行注释27 分钟前
前端数据加密:保护用户数据的第一道防线
前端
纪伊路上盛名在32 分钟前
记1次BioPython Entrez模块Elink的debug
前端·数据库·python·debug·工具开发
xiaoxue..34 分钟前
React 之 Hooks
前端·javascript·react.js·面试·前端框架
旧梦吟39 分钟前
脚本网页 三人四字棋
前端·数据库·算法·css3·html5
莫物41 分钟前
element el-table表格 添加唯一标识
前端·javascript·vue.js
我看刑42 分钟前
【已解决】el-table 前端分页多选、跨页全选等
前端·vue·element
我会一直在的1 小时前
Fiddler基础使用介绍
前端·测试工具·fiddler
小明记账簿1 小时前
前端文件流下载方法封装
前端
IT_陈寒1 小时前
Vite 5大优化技巧:让你的构建速度飙升50%,开发者都在偷偷用!
前端·人工智能·后端