JSFiddle - React, Tailwind, and code Playground
by Stalk
HTML
<b id="ball"></b>
CSS
#ball {
display: block;
width: 20px;
height: 20px;
border-radius: 50%;
background: red;
position: absolute;
top: 200px;
left: 200px;
}
JavaScript
const screenWidth = document.documentElement.clientWidth
const screenHeight = document.documentElement.clientHeight
let vector = {x: 1.5, y: -2.5}
function step(timestamp) {
const {left:x, top:y} = ball.getBoundingClientRect()
// change direction
if (x < 0) vector.x *= -1
if (y < 0) vector.y *= -1
if (x > screenWidth) vector.x *= -1
if (y > screenHeight) vector.y *= -1
ball.style.left = x + vector.x + 'px'
ball.style.top = y + vector.y + 'px'
//console.log(x, y, vector)
requestAnimationFrame(step);
}
requestAnimationFrame(step);