萤火虫 面向对象

整体效果

整体效果.jpg
后面是一张背景图
萤火虫背景图.jpg

萤火虫也是一张图片,是从网上下载的。


star.jpg
html
<div id="bg"></div>
css
*{
    margin: 0;
    padding: 0;
}
html,body{
    width: 100%;
    height: 100%;
}
#bg{
    background: url(img/bg.jpg) no-repeat center;/*这就是那张大的背景图*/
    width: 100%;
    height: 100%;
    background-size:cover;
    position: relative;
}
img{
    width: 12px;
    height: 12px;
    position: absolute;
    top: 0;
    left: 0;
    /*这里对星星图的位置做了绝对定位,然后通过js改变星星的left和top值,以达到萤火虫飞舞的效果*/
}
js
function Firebug(){
    this.oBg = document.getElementById("bg");
    this.oImg = document.createElement("img");
};
Firebug.prototype.show = function(){//显示萤火虫
    this.oImg.src = 'img/star.jpg';
    this.oImg.style.left = this.posiX + 'px';
    this.oImg.style.top = this.posiY + 'px';
    this.oBg.appendChild( this.oImg );
    return this;
};

Firebug.prototype.posi = function(){//生成萤火虫随机位置
    this.posiX = this.randomNum( window.innerWidth - 100 ) ;
    this.posiY = this.randomNum( window.innerHeight - 100 ) ;
    return this;
};
Firebug.prototype.speed = function(){//生成萤火虫随机速度
    this.speedNum = ( this.randomNum( 10 ) + 5 )*1000;
    return this;
};

Firebug.prototype.fly = function(){//让萤火虫飞舞起来
    var This = this;
    this.oImg.move({'left':this.posiX,'top':this.posiY,},this.speedNum,function(){
        This.posi().speed().fly();
    });
};
Firebug.prototype.size = function(){//生成萤火虫随机大小
    this.oImg.style.width = ( this.randomNum( 14 ) + 12 ) + 'px';
    this.oImg.style.height = ( this.randomNum( 14 ) + 12 ) + 'px';
    return this;
}
Firebug.prototype.randomNum = function( num ){//生成随机数
    return Math.floor( Math.random()*num );
};

var fireBug = [];
for( var i=0;i<50;i++ ){
    fireBug[i] = new Firebug();
    fireBug[i].posi().show().size().speed().posi().fly();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容