码迷,mamicode.com
首页 > 其他好文 > 详细

五彩小球案例

时间:2019-07-25 00:14:41      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:lan   htm   har   yellow   padding   nod   red   absolute   idt   

 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, #box{width: 100%;height: 100%;}
 9         #box{background-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)
       }
   }
};

 

五彩小球案例

标签:lan   htm   har   yellow   padding   nod   red   absolute   idt   

原文地址:https://www.cnblogs.com/zhangzhengyang/p/11241514.html

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