<! DOCTYPE html>
<meta charset= "UTF-8" >
<meta name= "viewport" content= "Width=device-width, initial-scale=1.0" >
<meta http-equiv= "x-ua-compatible" content= "Ie=edge" >
<title>balls motions</title>
<style>
* {
margin:0;
padding:0;
}
Body {
WIDTH:100VW;
HEIGHT:100VH;
Background-color: #333;
/* 33~CC, 51~204 */
}
. Ball {
width:100px;
height:100px;
Background: #369;
border-radius:50%;
position:fixed;
}
</style>
<body>
<div id= "desktop" ></div>
<script>
Wide screen height
var maxw = window.innerwidth;
var maxh = window.innerheight;
Dynamic Fetch screen Width high value
function Winfo () {
Maxw = window.innerwidth;
Maxh = Window.innerheight;
}
Window.onresize = Winfo;
Random function
function rand (A, b) {
Return Math.Round (Math.random () * (B-A) + a);
}
var max = 500;
Add a Ball (object) label
var str = (new Array (max + 1)). Join (' <div class= ' ball ' ></div> ');
for (var i = 0; i < max; i++) {
str + = ' <div class= ' ball ' ></div> ';
// }
Document.queryselector (' #desktop '). InnerHTML = str;
Document.queryselector (' #desktop '). InnerHTML =
(New Array (max + 1)). Join (' <div class= ' ball ' ></div> ');
var objs = Document.queryselectorall ('. Ball ');
var balls = [];
Objs.foreach (function (EL) {
var d = rand (5, 20);
Balls.push ({
Obj:el,
D:D,
X:rand (0, maxw-d),
Y:rand (0, maxh-d),
Dx:rand (0, 1)? 1:-1,
Dy:rand (0, 1)? 1:-1,
Sx:rand (2, 10),
Sy:rand (2, 10),
Bg:
"Rgba (" +
Rand (51, 204) + "," +
Rand (51, 204) + "," +
Rand (51, 204) + "," +
Rand (30, 80)/100 + ")"
});
});
Console.log ("All Balls:", balls);
Balls[0].obj.style.left = balls[0].x + ' px ';
Balls[0].obj.style.top = balls[0].y + ' px ';
Balls[0].obj.style.background = balls[0].bg;
Movement
Function Motion () {
Balls.foreach (function (el, index, arr) {
for (var i = 0; i < balls.length; i++) {
var el = balls[i];
el.x + = El.dx * EL.SX;
EL.Y + = El.dy * EL.SY;
if (el.x > Maxw && el.dx > 0) {
el.x =-EL.D;
El.dy = rand (0, 1)? 1:-1;
EL.SX = rand (1, 5);
}
if (el.x < -100 && EL.DX < 0) {
el.x = MAXW;
El.dy = rand (0, 1)? 1:-1;
EL.SX = rand (1, 5);
}
if (El.y > Maxh && el.dy > 0) {
El.y =-EL.D;
EL.DX = rand (0, 1)? 1:-1;
El.sy = rand (1, 5);
}
if (El.y < -100 && El.dy < 0) {
El.y = Maxh;
EL.DX = rand (0, 1)? 1:-1;
El.sy = rand (1, 5);
}
Set appearance
El.obj.style.width = el.d + ' px ';
El.obj.style.height = el.d + ' px ';
El.obj.style.left = el.x + ' px ';
El.obj.style.top = el.y + ' px ';
El.obj.style.background = el.bg;
}
// });
Appointment next time
SetTimeout (motion, 0);
}
Motion ();
</script>
</body>
Random direction of random ball movement, native JS