实现弹力球效果,碰到屏幕边框弹回,效果如下
代码如下:
<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 edgesif (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>