五彩小球案例

Posted zhangzhengyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了五彩小球案例相关的知识,希望对你有一定的参考价值。

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>五彩小球</title>
 6     <style>
 7         *margin: 0;padding: 0;list-style: none;
 8         html, body, #boxwidth: 100%;height: 100%;
 9         #boxbackground-color: #000;
10     </style>
11 </head>
12 <body>
13     <div id="box"></div>
14 
15 <script src="js/Underscore-min.js"></script>
16 <script src="js/Ball.js"></script>
17 <script>
18 
19     // 装小球
20     var ballArr = [];
21     // 颜色数组
22     var colorArr = [‘red‘, ‘green‘, ‘blue‘, ‘yellow‘, ‘orange‘, ‘purple‘, ‘pink‘];
23 
24     // 1. 获取盒子
25     var box = document.getElementById(‘box‘);
26     // 2. 监听鼠标的移动
27     box.addEventListener(‘mousemove‘, function (ev) 
28         var ball = new Ball(
29             ‘parentId‘: ‘box‘,
30             ‘left‘: ev.clientX,
31             ‘top‘: ev.clientY,
32             ‘bgColor‘: colorArr[_.random(0, colorArr.length-1)]
33         );
34         // ball.render();
35         ballArr.push(ball);
36     );
37     // 3. 定时器
38     setInterval(function () 
39         // 清除之前的状态
40         for (var i = 0; i < box.children.length; i++) 
41             box.children[i].remove();
42         
43 
44         // 小球的绘制和移动
45         for(var j=0; j<ballArr.length; j++)
46             ballArr[j].render();
47             ballArr[j].update(ballArr);
48         
49     , 50);
50 </script>
51 </body>
52 </html>
function Ball(option) 
    option = option || ;
    // 1. 属性
    this.parentId = option.parentId;
    this.r = 60;
    this.left = option.left || 0;
    this.top = option.top || 0;
    this.bgColor = option.bgColor || ‘red‘;

    // 2. 变化量
    this.dX = _.random(-10, 10);
    this.dY = _.random(-10, 10);
    this.dR = _.random(1, 3);


Ball.prototype = 
   constructor: Ball,
   render: function () 
       var parentNode = document.getElementById(this.parentId);
       var childNode = document.createElement(‘div‘);
       childNode.style.width = this.r + ‘px‘;
       childNode.style.height = this.r + ‘px‘;
       childNode.style.backgroundColor = this.bgColor;
       childNode.style.borderRadius = ‘50%‘;
       childNode.style.position = ‘absolute‘;
       childNode.style.left = this.left + ‘px‘;
       childNode.style.top = this.top + ‘px‘;
       parentNode.appendChild(childNode);
   ,
   update: function (ballArr) 
       this.left += this.dX;
       this.top += this.dY;
       this.r -= this.dR;
       if(this.r <= 0)
           ballArr = _.without(ballArr, this)
       
   
;

 

以上是关于五彩小球案例的主要内容,如果未能解决你的问题,请参考以下文章

前端css综合案例1-7:新闻页面五彩导航产品模块快报模块学成在线首页CSS三角土豆案例

五彩导航案例

JavaScript动画-小案例:小球运动

炫彩小球案例

炫彩小球案例

(译)LearnOpenGL实际案例Breakout:小球