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>
相关推荐
m0_5287238116 分钟前
HTML中,title和h1标签的区别是什么?
前端·html
Dark_programmer17 分钟前
html - - - - - modal弹窗出现时,页面怎么能限制滚动
前端·html
GDAL22 分钟前
HTML Canvas clip 深入全面讲解
前端·javascript·canvas
禾苗种树23 分钟前
在 Vue 3 中使用 ECharts 制作多 Y 轴折线图时,若希望 **Y 轴颜色自动匹配折线颜色**且无需手动干预,可以通过以下步骤实现:
前端·vue.js·echarts
贵州数擎科技有限公司1 小时前
使用 Three.js 实现流光特效
前端·webgl
JustHappy1 小时前
「我们一起做组件库🌻」做个面包屑🥖,Vue的依赖注入实战💉(VersakitUI开发实录)
前端·javascript·github
拉不动的猪1 小时前
刷刷题16
前端·javascript·面试
祈澈菇凉2 小时前
如何结合使用thread-loader和cache-loader以获得最佳效果?
前端
垣宇2 小时前
Vite 和 Webpack 的区别和选择
前端·webpack·node.js
java1234_小锋2 小时前
一周学会Flask3 Python Web开发-客户端状态信息Cookie以及加密
前端·python·flask·flask3