javascript彩色喷泉- Blue-Dream - 博客园

【实例演示】

 

 

【程序源码】

/**
 * 小球类 Ball
 * @param {number} diameter 直径
 
*/
 
var Ball = function(diameter, x, y, vx, vy) {
    
var ball = document.createElement('div');
    
var r = Math.floor(Math.random() * 255);
    
var g = Math.floor(Math.random() * 255);
    
var b = Math.floor(Math.random() * 255);
    ball.style.width 
= ball.style.height = diameter + 'px';
    ball.style.backgroundColor 
= 'rgb('+r+''+g+''+b+')';
    ball.style.left 
= x + 'px'; ball.style.top = y + 'px'; ball.vx = vx; ball.vy = vy; ball.style.position = 'absolute';
    
return ball;
 };

 
function T$(id) { return document.getElementById(id) }
/**
 * 喷泉主类 Fountain
 * @param {string} 舞台ID
 * @param {number} 水滴数目
 * @param {number} 重力加速度
 
*/
 
var Fountain = function(stage, count, gravity) {
    
this.stage = T$(stage);
    
this.count = count;
    
this.gravity = gravity;
    
this.timer = null;
 };

 Fountain.prototype 
= {
    constructor: Fountain,
    initialize: 
function() {
        
// 生成一定数目的随机颜色小球
        var self = this, count = self.count, j = 0,
            frag 
= document.createDocumentFragment(),
            stage 
= self.stage, gravity = self.gravity;
        
// 设置小球参数(直径, 半径,  舞台位置)
        var diameter = 4, radius = diameter / 2, x = stage.clientWidth / 2, y = stage.clientHeight;
        
var balls = new Array();
        
for (; j < count; j++) {
            
var ball = new Ball(diameter, x, y, Math.random() * 4 - 1, Math.random() * -10 - 10);
            balls[j] 
= ball;
            frag.appendChild(ball);
        } 
        T$(
'fountain').innerHTML = '';
        T$(
'fountain').appendChild(frag);
        clearTimeout(self.timer);
        
function Run() {
            
for (var i = 0, len = balls.length; i < len; i++) {
                
var ball = balls[i];
                ball.vy 
+= gravity;
                ball.style.left 
= (ball.offsetLeft + ball.vx) + 'px';
                ball.style.top 
= (ball.offsetTop + ball.vy) + 'px';
                
// 边界检测
                if (ball.offsetLeft - radius > x || ball.offsetLeft + radius < 0
                    
|| ball.offsetTop - radius > y || ball.offsetTop + radius < 0
                {
                    ball.style.left 
= x + 'px';
                    ball.style.top 
= y + 'px';
                    ball.vx 
= Math.random() * 4 - 1;
                    ball.vy 
= Math.random() * -10 - 10;
                }
            } 
            self.timer 
= setTimeout(Run, 10);
        }
        Run();
    }
 };

 
// 在舞台中央生成30个彩色水滴. 重力加速度为.5
 var fountain = new Fountain('stage'300.5);
 T$(
'run').onclick = function() {
    fountain.initialize();
 }
 T$(
'stop').onclick = function() {
    clearTimeout(fountain.timer);
 }

 

 

【源码下载】 

 

郑重声明:资讯 【javascript彩色喷泉- Blue-Dream - 博客园】由 发布,版权归原作者及其所在单位,其原创性以及文中陈述文字和内容未经(企业库qiyeku.com)证实,请读者仅作参考,并请自行核实相关内容。若本文有侵犯到您的版权, 请你提供相关证明及申请并与我们联系(qiyeku # qq.com)或【在线投诉】,我们审核后将会尽快处理。
—— 相关资讯 ——