介绍
小编给大家分享一下JavaScript中实现烟花绽放动画效果的方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!
,,,,,先编写一个烟花绽放的动画效果。
,,,,,放烟花时,一个烟花可分为两个阶段:(1)烟花上升到空中;(2)烟花炸开成碎片,炸开的碎片慢慢消散。
,,,,,为此抽象出两个对象类:烟花和粒子。其中,烟花用于表示一个烟花对象,粒子用于表示一个烟花炸开后的各碎片。
,,,,,烟花对象类定义6个属性:表示烟花上升轨迹中各点的坐标(x, y),烟花弧状轨迹的偏转角度角,上升阶段水平和垂直方向的位移改变量xSpeed和ySpeed,烟花的色彩色相色彩。
,,,,,坐标属性值y的初始值取画布的高度,表示烟花从地面上升到空中,其余各属性的初始值采用随机数确定。具体定义如下:
烟花()函数 { 这一点。x=canvas.width/4 * (1 + 3 * math . random ()); 这一点。y=画布。高度- 15; 这一点。角=Math . random() *数学。π/4 -数学。π/6; 这一点。xSpeed=sin (this.angle) * (6 + math . random () * 7); 这一点。ySpeed=-Math.cos (this.angle) * (6 + math . random () * 7); 这一点。颜色=Math.floor (math . random () * 360); }
,,,,,烟花对象类定义3个方法:绘制烟花上升轨迹的方法画(),烟花上升时坐标改变方法更新()和烟花炸开方法()爆炸。绘制烟花轨迹时,在各点(x, y)处绘制一个宽度为5,高度为15的填充小矩形表示一个轨迹点。烟花上升时,垂直方向速度ySpeed初始值为负的,每次上升时,ySpeed加上一个正值,表示上升在减速,当ySpeed的值大于0时,烟花上升到顶了(不能再上升),就炸开为70个碎片。具体方法的实现见后面的HTML文件内容。
,,,,,,粒子对象类定义8个属性:表示碎片散开轨迹中各点的坐标(x, y)、碎片弧状轨迹的偏转角度角,散开时水平和垂直方向的位移改变量xSpeed和ySpeed,碎片的色彩色相色调,表示碎片小圆的半径大小、碎片的亮度轻。
& lt; html> & lt; head> & lt; title>烟花绽放& lt;/title> & lt;/head> & lt; body> & lt;帆布id=癿yCanvas"宽度=?00”;身高=?00”;比; & lt;/canvas> & lt;脚本类型=拔谋?javascript"比; 画布var=. getelementbyid (& # 39; myCanvas& # 39;); ctx=canvas.getContext (& # 39; 2 d # 39;); var烟花=[]; var粒子=[]; var counter=0; 烟花()函数 { 这一点。x=canvas.width/4 * (1 + 3 * math . random ()); 这一点。y=画布。高度- 15; 这一点。角=Math . random() *数学。π/4 -数学。π/6; 这一点。xSpeed=sin (this.angle) * (6 + math . random () * 7); 这一点。ySpeed=-Math.cos (this.angle) * (6 + math . random () * 7); 这一点。颜色=Math.floor (math . random () * 360); } Firework.prototype。画=function () { ctx.save (); ctx.translate(这一点。x, this.y); ctx.rotate (Math.atan2(这一点。ySpeed this.xSpeed) +数学。π/2); ctx。fillStyle='奥软($ {。色调},100%,50%); ctx。fillRect (0, 0、5、15); ctx.restore (); } Firework.prototype。更新=function () { 这一点。x= + this.xSpeed; 这一点。y= + this.ySpeed; 这一点。ySpeed +=0.1; } Firework.prototype。爆炸=function () { (var=0;我& lt;70;我+ +) { 粒子。推动(新粒子(这一点。x,这。y, this.hue)); } } 函数的粒子(x, y,色调) { 这一点。x=x; 这一点。y=y; 这一点。颜色=色调; 这一点。明度=50; 这一点。大?15 + math . random () * 10; 这一点。角=math . random () * 2 * Math.PI; 这一点。xSpeed=Math.cos (this.angle) * (1 + math . random () * 6); 这一点。ySpeed=sin (this.angle) * (1 + math . random () * 6); } Particle.prototype。画=function () { ctx。fillStyle='奥软($ {。色调},100%,$ {this.lightness} %) '; ctx.beginPath (); ctx.arc(这一点。x,这。y。大小、0、2 * Math.PI); ctx.closePath (); ctx.fill (); } Particle.prototype。更新=函数(指数) { 这一点。ySpeed +=0.05; 这一点。大?size * 0.95; 这一点。x= + this.xSpeed; 这一点。y= + this.ySpeed; 如果(this.sizeJavaScript中实现烟花绽放动画效果的方法