效果预览:
这是我在网上看到的一个效果,觉得还是很不错的,就研究了一下源码,今天给大家分享一下,其实也很简单。
简单的简述一下原理:
首先是用css在dom创建的div里面画一个若干个圆,圆的大小是随机数,圆的数量也是随机设置的,当然颜色也是随机的,
最后是移动速度,然后拿到屏幕的宽高,下一步就是让小球运动起来,达到边界值的时候就改变方向,循环执行fn的运动的函数。
源码:
.ball { position: absolute; top: 0; left: 0; width: 100px; height: 100px; background: radial-gradient(circle, #fff, #fff600); border-radius: 50%; }
// 创建[1,11)个小球 var mdAttr = document.createDocumentFragment(); var OBall = [];//小球对象数组 for (var i = 0; i < random(5,20); i++) { OBall[i] = document.createElement("div"); OBall[i].setAttribute("class", "ball"); var cirR = random(80,100);//小球半径 OBall[i].style.width = cirR * 2 + "px"; OBall[i].style.height = cirR * 2 + "px"; OBall[i].style.background = "radial-gradient(circle," + randomColor() + "," + randomColor() + ")"; mdAttr.appendChild(OBall[i]); OBall[i].startX = random(1,10);//初始位置X 可以自己设置位置,不一定是非要从左上角 OBall[i].startY = random(1,10);//初始位置Y OBall[i].Vx = random(3,10);//水平增加距离 这个速度是随机增加的,不然没有随机的效果 OBall[i].Vy = random(3,10);//垂直增加距离 } document.body.appendChild(mdAttr); //获取浏览器窗口宽高 var W,H; window.onresize = (function(){ W = window.innerWidth, H = window.innerHeight; })(); //运动 ~ ! void + a= (function fn()) ~ function fn() { OBall.forEach(function (ball) { var MaxH = H - ball.offsetHeight,//获取小球位置的最大值,以免超过边界 MaxW = W - ball.offsetWidth; ball.startX += ball.Vx;//改变小球位置 ball.startY += ball.Vy; if(ball.startX >= MaxW || ball.startX <=0){//若小球位置超出最大值和最小值就改变方向 ball.Vx *= -1; ball.style.background = "radial-gradient(circle," + randomColor() + "," + randomColor() + ")"; ball.startX = Math.max(0,ball.startX); ball.startX = Math.min(ball.startX,MaxW); } if(ball.startY >= MaxH || ball.startY <=0){ ball.Vy *= -1; ball.style.background = "radial-gradient(circle," + randomColor() + "," + randomColor() + ")"; ball.startY = Math.max(0,ball.startY); ball.startY = Math.min(ball.startY,MaxW); } ball.style.left = ball.startX + "px";//设置小球当前位置 ball.style.top = ball.startY + "px"; }); requestAnimationFrame(fn);//循环 }(); //颜色随机 function randomColor() { var r = Math.floor(Math.random() * 256), g = Math.floor(Math.random() * 256), b = Math.floor(Math.random() * 256); return "rgb(" + r + "," + g + "," + b + ")"; } //取[min,max)之间的随机值 function random(min,max){ return Math.random(max-min)+min; }
源码的注释写的还是很清楚的,看还是看的明白的。