<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.ball-box{
background: #f4f4f4;
width: 200px;
height: 200px;
position: relative;
}
.ball{
background: red;
border-radius:50%;
width: 22px;
height: 22px;
position: absolute
}
</style>
<body>
<div class="ball-box">
<div class="ball"></div>
</div>
</body>
</html>
<script>
const ball = document.getElementsByClassName("ball")[0];
const box = document.getElementsByClassName("ball-box")[0];
move();
function move(){
var speed = 2;
let ballX = (box.offsetWidth - ball.offsetWidth) * Math.random();
let ballY = (box.offsetHeight - ball.offsetHeight) * Math.random();
ball.style.left = ballX + 'px';
ball.style.top = ballY + 'px';
var theta = 2 * Math.PI * Math.random();
var speedX = speed * Math.cos(theta);
var speedY = speed * Math.sin(theta);
setInterval(()=>{
ballX += speedX;
ballY += speedY;
ball.style.left = ballX + 'px';
ball.style.top = ballY + 'px';
if(ballX + ball.offsetWidth >= box.offsetWidth || ballX <= 0) {
speedX = -speedX;
}
if(ballY + ball.offsetHeight >= box.offsetHeight || ballY <= 0) {
speedY = -speedY;
}
},120)
}
</script>