球球
-
效果
-
代码
<!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>
<style>
.game {
position: relative;
width: 800px;
height: 600px;
border: 1px solid rgb(0, 0, 0);
background-color: rgb(224, 255, 255);
margin: 0 auto;
}
.ball {
position: absolute;
border-radius: 50%;
}
.fire_but {
margin-left: 660px;
}
</style>
</head>
<body>
<div class="game"></div>
<button class="fire_but">发射小球</button>
<button class="del_ball">删除小球</button>
<script src="../js/ballMove.js"></script>
</body>
</html>
var game = document.getElementsByClassName("game")[0]
var fire_but = document.getElementsByClassName("fire_but")[0]
var del_ball = document.getElementsByClassName("del_ball")[0]
var arr = []
// 生成随机数
function my_random(min, max) {
return parseInt(Math.random() * (max - min)) + min
}
// 创建小球
function createBall() {
// 创建一个元素
var ball = document.createElement("div")
ball.className = "ball"
game.append(ball)
arr.push(ball)
ball.bian = my_random(40, 80)
ball.x = my_random(0, game.offsetWidth - ball.bian)
ball.y = my_random(0, game.offsetHeight - ball.bian)
ball.speedX = my_random(8, 20)
ball.speedY = my_random(8, 20)
ball.directionX = my_random(0, 11) % 2 == 0 ? "a" : "d"
ball.directionY = my_random(0, 11) % 2 == 0 ? "w" : "s"
ball.style.width = ball.bian + "px"
ball.style.height = ball.bian + "px"
ball.style.backgroundColor = "rgba(" + my_random(0, 255) + "," + my_random(0, 255) + "," + my_random(0, 255) + "," + my_random(1, 10) * 0.1 + ")"
}
// 为发射小球按钮设置点击事件
fire_but.onclick = function() {
createBall()
}
// 小球移动
function ballMove() {
for (var i = 0; i < arr.length; i++) {
if (true) {
if (arr[i].directionY == "w") {
arr[i].y = arr[i].y - arr[i].speedY
console.log("上")
}
if (arr[i].directionY == "s") {
arr[i].y = arr[i].y + arr[i].speedY
console.log("下")
}
if (arr[i].directionX == "a") {
arr[i].x = arr[i].x - arr[i].speedX
console.log("左")
}
if (arr[i].directionX == "d") {
arr[i].x = arr[i].x + arr[i].speedX
console.log("右")
}
if (arr[i].x < 0) {
arr[i].x = 0
arr[i].directionX = "d"
}
if (arr[i].x >= game.offsetWidth - arr[i].offsetWidth - 2) {
arr[i].x = game.offsetWidth - arr[i].offsetWidth - 3
arr[i].directionX = "a"
}
if (arr[i].y < 0) {
arr[i].y = 0
arr[i].directionY = "s"
}
if (arr[i].y >= game.offsetHeight - arr[i].offsetHeight - 2) {
arr[i].y = game.offsetHeight - arr[i].offsetHeight - 3
arr[i].directionY = "w"
}
arr[i].style.left = arr[i].x + "px"
arr[i].style.top = arr[i].y + "px"
}
}
requestAnimationFrame(ballMove)
}
ballMove()
// 删除小球
del_ball.onclick = function() {
if (arr.length > 0) {
arr[arr.length - 1].remove()
arr.splice(arr.length - 1, 1)
}
}
链接:https://pan.baidu.com/s/1MmLHyvyYGCzLOu5TBwOjrQ
提取码:rgba