html加js生成的图片随机运动,js实现小球随机运动 |
您所在的位置:网站首页 › 小球运动轨迹图片 › html加js生成的图片随机运动,js实现小球随机运动 |
效果图: 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 = box.offsetHeight || ballY |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |