JavaScript动画-小案例:小球运动
Posted dqy95
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript动画-小案例:小球运动相关的知识,希望对你有一定的参考价值。
最近的讲js运动框架时,做了一个小案例,随机生成几个小球,然后让他们在页面中跳动,碰到边界就弹回来并修改颜色。效果如下:
代码如下:
1 <!doctype html> 2 <html> 3 4 <head> 5 <meta charset="utf-8"> 6 <meta name="Keywords" content="28-JS作业小球运动"> 7 <meta name="Description" content="28-JS小球运动"> 8 <title>JS-小球运动</title> 9 <style> 10 .ball { 11 position: absolute; 12 top: 0; 13 left: 0; 14 width: 100px; 15 height: 100px; 16 background: radial-gradient(circle, #fff, #fff600); 17 border-radius: 50%; 18 } 19 </style> 20 </head> 21 22 <body> 23 <!-- <div class="ball"></div> --> 24 <script> 25 26 // 创建[1,11)个小球 27 var mdAttr = document.createDocumentFragment(); 28 var OBall = [];//小球对象数组 29 for (var i = 0; i < random(5,20); i++) { 30 OBall[i] = document.createElement("div"); 31 OBall[i].setAttribute("class", "ball"); 32 33 var cirR = random(30,50);//小球半径 34 OBall[i].style.width = cirR * 2 + "px"; 35 OBall[i].style.height = cirR * 2 + "px"; 36 OBall[i].style.background = "radial-gradient(circle," + randomColor() + "," + randomColor() + ")"; 37 mdAttr.appendChild(OBall[i]); 38 39 OBall[i].startX = random(1,10);//初始位置X 40 OBall[i].startY = random(1,10);//初始位置Y 41 OBall[i].Vx = random(3,10);//水平增加距离 42 OBall[i].Vy = random(3,10);//垂直增加距离 43 } 44 document.body.appendChild(mdAttr); 45 46 //获取浏览器窗口宽高 47 var W,H; 48 window.onresize = (function(){ 49 W = window.innerWidth, 50 H = window.innerHeight; 51 })(); 52 53 //运动 54 ~function fn() { 55 OBall.forEach(function (ball) { 56 var MaxH = H - ball.offsetHeight,//获取小球位置的最大值,以免超过边界 57 MaxW = W - ball.offsetWidth; 58 ball.startX += ball.Vx;//改变小球位置 59 ball.startY += ball.Vy; 60 if(ball.startX >= MaxW || ball.startX <=0){//若小球位置超出最大值和最小值就改变方向 61 ball.Vx *= -1; 62 ball.style.background = "radial-gradient(circle," + randomColor() + "," + randomColor() + ")"; 63 ball.startX = Math.max(0,ball.startX); 64 ball.startX = Math.min(ball.startX,MaxW); 65 } 66 if(ball.startY >= MaxH || ball.startY <=0){ 67 ball.Vy *= -1; 68 ball.style.background = "radial-gradient(circle," + randomColor() + "," + randomColor() + ")"; 69 ball.startY = Math.max(0,ball.startY); 70 ball.startY = Math.min(ball.startY,MaxW); 71 } 72 ball.style.left = ball.startX + "px";//设置小球当前位置 73 ball.style.top = ball.startY + "px"; 74 75 }); 76 requestAnimationFrame(fn);//循环 77 }(); 78 79 //颜色随机 80 function randomColor() { 81 var r = Math.floor(Math.random() * 256), 82 g = Math.floor(Math.random() * 256), 83 b = Math.floor(Math.random() * 256); 84 return "rgb(" + r + "," + g + "," + b + ")"; 85 } 86 //取[min,max)之间的随机值 87 function random(min,max){ 88 return Math.random(max-min)+min; 89 } 90 </script> 91 </body> 92 93 </html>
以上是关于JavaScript动画-小案例:小球运动的主要内容,如果未能解决你的问题,请参考以下文章