Отскок шарика от краев границ блока?

1,00
р.
В родительском блоке имеется шар:


body { background: black } .box { position: relative overflow: hidden margin: 0 auto width: 500px height: 300px border-radius: 5px box-shadow: inset 0 0 2px black background-color: white } .ball { position: absolute width: 20px height: 20px border-radius: 100% background-color: black box-shadow: inset -5px -5px 5px rgba(0, 0, 0, .5), 15px 15px 2px rgba(0, 0, 0, .05) }


Как можно заставить его бесконечно двигаться и отскакивать от краев границ этого блока?

Ответ
if(шарик.x < 0 || шарик.x > контейнер.width - шарик.width) { скорость шарика по оси X умножаем на -1 }
if(шарик.y < 0 || шарик.y > контейнер.height - шарик.height) { скорость шарика по оси Y умножаем на -1 }


const container_info = { w: container.getBoundingClientRect().width, h: container.getBoundingClientRect().height }
const ball_info = { x:0,y:0, vx:4,vy:4, w: ball.getBoundingClientRect().width, h: ball.getBoundingClientRect().height }
function updatePositionInformation(info) { info.x += info.vx info.y += info.vy }
function translateDomElement(el, info) { el.style.transform = `translate(${info.x}px, ${info.y}px)` }
function checkXPosition(el_info, container_info) { return el_info.x < 0 || el_info.x > container_info.w - el_info.w }
function checkYPosition(el_info, container_info) { return el_info.y < 0 || el_info.y > container_info.h - el_info.h }
function boundaries(el_info, x_out, y_out) { if(x_out) el_info.vx *= -1 if(y_out) el_info.vy *= -1 }
function render() { updatePositionInformation(ball_info) translateDomElement(ball, ball_info) boundaries( ball_info, checkXPosition(ball_info, container_info), checkYPosition(ball_info, container_info), ) requestAnimationFrame(render) }
render() body { height: 100vh margin: 0 display: flex align-items: center justify-content: center background-color: black }
#container { position: relative width: 250px height: 150px background-color: white }
#ball { position: absolute width: 15px height: 15px border-radius: 50% background-color: black }