多语言展示
当前在线:587今日阅读:103今日分享:49

怎么用javascript模拟烟花?

烟花的燃放,当真是缤纷多彩。本文介绍一下在网页里面,模拟烟花燃放的效果。
工具/原料
1

电脑

2

浏览器

3

notepad

方法/步骤
1

notepad用来编辑html代码。

2

烟花在黑夜里燃放,才有看头。所以,用黑色背景来模拟夜色。js Effect of fireworks

3

用一个宽27像素、高270像素的红色长方形来表示烟花;鼠标在网页某个位置点击一下,烟花就会发射到相应位置:document.onclick=function (ev){    var oEvent=ev||event;    var aDiv=[];    var oDiv=null;    var _oDiv=document.createElement('div');    var i=0;    var x=oEvent.clientX;    var y=oEvent.clientY;    _oDiv.style.position='absolute';    _oDiv.style.background='red';    _oDiv.style.width='27px';    _oDiv.style.height='270px';    _oDiv.style.left=oEvent.clientX+'px';    _oDiv.style.top=document.documentElement.clientHeight+'px';    document.body.appendChild(_oDiv);    var t=setInterval(function (){        if(_oDiv.offsetTop<=y)        {            clearInterval(t);            show();            document.body.removeChild(_oDiv);        }        _oDiv.style.top=_oDiv.offsetTop-30+'px';    }, 30);};

4

烟花在爆炸的时候,烟花消失,取而代之的是100个重叠在一起的彩色方块:    function show()    {        var oDiv=null;        for(i=0;i<100;i++)        {            oDiv=document.createElement('div');            oDiv.style.width='18px';            oDiv.style.height='18px';            oDiv.style.background='#'+Math.ceil(Math.random()*0xEFFFFF+0x0FFFFF).toString(16);            oDiv.style.position='absolute';            oDiv.style.left=x+'px';            oDiv.style.top=y+'px';            var a=Math.random()*360;            //oDiv.speedX=Math.random()*40-20;            //oDiv.speedY=Math.random()*40-20;            oDiv.speedX=Math.sin(a*180/Math.PI)*20*Math.random();            oDiv.speedY=Math.cos(a*180/Math.PI)*20*Math.random();            document.body.appendChild(oDiv);            aDiv.push(oDiv);        }    }

5

爆炸,重叠在一起的100个彩色方块随机地向四周抛射散落:    setInterval(doMove, 30);    function doMove()    {        for(i=0;idocument.documentElement.clientWidth || aDiv[i].offsetTop<0 || aDiv[i].offsetTop>document.documentElement.clientHeight)            {                document.body.removeChild(aDiv[i]);                aDiv.splice(i, 1);            }        }    }

6

整体代码布局如下图。

注意事项
1

把上述代码保存为html,然后可以用浏览器打开。

2

鼠标点击网页,就可以实现烟花燃放的效果。

3

鼠标不要点的国语激烈,否则电脑会很卡。

推荐信息