js实现小球随机运动

效果图:
js实现小球随机运动_第1张图片

HTML

  

style:

.box{
  width:300px;
  height:400px;
  background-color:green;
  opacity:0.5;
  margin:auto;
  position:relative;
}
.ball{
  width:20px;
  height:20px;
  border-radius:50%;
  background-color:yellow;
  position:absolute;
}

javascript:

window.onload = function() {
       var ball = document.getElementsByClassName('ball')[0];
       var box = document.getElementsByClassName('box')[0];
    function ballMove() {
      var speed = 2;//定义总体速度
      //随机设置小球的初始位置
      var ballX = (box.offsetWidth - ball.offsetWidth) * Math.random();
      var ballY = (box.offsetHeight - ball.offsetHeight) * Math.random();
      ball.style.left = ballX + 'px';
      ball.style.top = ballY + 'px';
      //随机设置小球在x和y方向的速度
      var theta = 2 * Math.PI * Math.random();
      var speedX = speed * Math.cos(theta);
      var speedY = speed * Math.sin(theta);
      setInterval(function() {
        //随机控制小球在X和Y方向上的位置
        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;
        }
      },10)
    }
    ballMove();
    }

你可能感兴趣的:(JS,实践案列)