js实现小球随机运动

本文介绍如何使用JavaScript创建一个动态效果,让小球在网页上进行随机运动。通过结合HTML、CSS和JavaScript,我们可以实现一个趣味性的交互式小球动画。内容包括小球的初始位置设定、运动方向与速度的随机生成以及碰撞检测等关键点。
摘要由CSDN通过智能技术生成

效果图:
在这里插入图片描述

HTML

  <div class='box'>
    <div class='ball'></div>
  </div>

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值