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>
相关推荐
PHP是世界上最好的语言11 分钟前
ComPDF预览本地正常,部署后白屏:检查资源、路径和许可
前端
kiros_wang13 分钟前
项目分包方案:模块拆分、跨模块组件与方法引用规范
前端
PedroQue9915 分钟前
unix-utils v0.2.0 发布:modal 全端统一,自绘窗口解决输入框难题
前端·uni-app
Csvn16 分钟前
网络优化
前端
代码猎人19 分钟前
前端怎么跟进生态新技术
前端
海阳皓辰网络科技有限公司19 分钟前
Vue3 冷库货位选择器:三级联动、扫码带出与批次混放校验
前端·vue.js
__sjfzllv___21 分钟前
在职前端Leader学习/转行 AI Agent -DAY81
前端
女生也可以敲代码23 分钟前
div上有红色下划线报错:JSX 元素隐式具有类型 “any“,因为不存在接口 “JSX.IntrinsicElements“。ts(7026)
前端
申君健248641827720225 分钟前
ArkTS 速成指南(写给有 TypeScript / 前端经验的开发者)
前端
代码猎人25 分钟前
前端怎么落地工程化规范
前端