码迷,mamicode.com
首页 > 移动开发 > 详细

大量随机圆球随机方向移动,原生js

时间:2017-10-03 14:55:32      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:随机函数   desktop   ack   position   meta   设置   height   length   set   

<!DOCTYPE html>
<html>

<head>
<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>
</head>

<body>
<div id="desktop"></div>
<script>
// 屏幕宽高
var maxw = window.innerWidth;
var maxh = window.innerHeight;
// 动态取屏幕宽高值
function winfo() {
maxw = window.innerWidth;
maxh = window.innerHeight;
}
window.onresize = winfo;
// 随机函数
function rand(a, b) {
return Math.round(Math.random() * (b - a) + a);
}
var max = 500;
// 添加小球(对象)标签
// 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;
// 运动
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);
}
// 设置外观
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;
}
// });
// 预约下次
setTimeout(motion, 0);
}
motion();
</script>
</body>

</html>

大量随机圆球随机方向移动,原生js

标签:随机函数   desktop   ack   position   meta   设置   height   length   set   

原文地址:http://www.cnblogs.com/AgilityJin/p/7623719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!