实例教程 HTML5 Canvas 超炫酷烟花绽放动画实现代码


Posted in HTML / CSS onNovember 05, 2014

这是一个很酷的HTML5 Canvas动画,它将模拟的是我们现实生活中烟花绽放的动画特效,效果非常逼真,但是毕竟是电脑模拟,带女朋友看就算了,效果还是差了点,呵呵。这个HTML5 Canvas动画有一点比较出色,就是其性能,Chrome上基本没有卡的感觉,就算你放出很多烟花也一样。

实例教程 HTML5 Canvas 超炫酷烟花绽放动画实现代码

下面我们来简单分析一下实现这款HTML5烟花特效的过程及代码,主要由HTML代码、CSS代码以及Javascript代码组成,当然javascript代码是最重要的。

HTML代码:

XML/HTML Code复制内容到剪贴板
  1. <div id=”gui”></div>  
  2. <div id=”canvas-container”> <div id=”mountains2″></div>    
  3. <div id=”mountains1″></div><div id=”skyline”></div> </div>  

HTML的结构非常简单,即构造了一个canvas容器,我们会利用JS在这个容器中生成一个Canvas对象。看最后的JS代码你就会知道了。

CSS代码:

CSS Code复制内容到剪贴板
  1. #canvas-container { background#000 url(bg.jpg); height400pxleft: 50%; margin: -200px 0 0 -300pxpositionabsolutetop: 50%; width600pxz-index: 2;   
  2. } canvas { cursorcrosshairdisplayblockpositionrelativez-index: 3;   
  3. } canvas:active { cursorcrosshair;   
  4. #skyline { backgroundurl(skyline.png) repeat-x 50% 0; bottombottom: 0; height135pxleft: 0; positionabsolutewidth: 100%; z-index: 1;       
  5. #mountains1 { backgroundurl(mountains1.png) repeat-x 40% 0; bottombottom: 0; height200pxleft: 0; positionabsolutewidth: 100%; z-index: 1;       
  6. #mountains2 { backgroundurl(mountains2.png) repeat-x 30% 0; bottombottom: 0; height250pxleft: 0; positionabsolutewidth: 100%; z-index: 1;       
  7. #gui { rightright: 0; positionfixedtop: 0; z-index: 3;   
  8. }  

CSS代码没什么特别,主要也就定义一下背景色和边框之类的。

接下来是最重要的Javascript代码。

Javascript代码:

JavaScript Code复制内容到剪贴板
  1. self.init = function(){       
  2.     self.dt = 0;   
  3.         self.oldTime = Date.now();   
  4.         self.canvas = document.createElement('canvas');                   
  5.         self.canvasContainer = $('#canvas-container'); var canvasContainerDisabled = document.getElementById('canvas-container');   
  6.         self.canvas.onselectstart = function() { return false;   
  7.         };   
  8.   
  9.         self.canvas.width = self.cw = 600;   
  10.         self.canvas.height = self.ch = 400;       
  11.   
  12.         self.particles = [];       
  13.         self.partCount = 30;   
  14.         self.fireworks = [];       
  15.         self.mx = self.cw/2;   
  16.         self.my = self.ch/2;   
  17.         self.currentHue = 170;   
  18.         self.partSpeed = 5;   
  19.         self.partSpeedVariance = 10;   
  20.         self.partWind = 50;   
  21.         self.partFriction = 5;   
  22.         self.partGravity = 1;   
  23.         self.hueMin = 150;   
  24.         self.hueMax = 200;   
  25.         self.fworkSpeed = 2;   
  26.         self.fworkAccel = 4;   
  27.         self.hueVariance = 30;   
  28.         self.flickerDensity = 20;   
  29.         self.showShockwave = false;   
  30.         self.showTarget = true;   
  31.         self.clearAlpha = 25;   
  32.   
  33.         self.canvasContainer.append(self.canvas);   
  34.         self.ctx = self.canvas.getContext('2d');   
  35.         self.ctx.lineCap = 'round';   
  36.         self.ctx.lineJoin = 'round';   
  37.         self.lineWidth = 1;   
  38.         self.bindEvents();               
  39.         self.canvasLoop();   
  40.   
  41.         self.canvas.onselectstart = function() { return false;   
  42.         };   
  43.   
  44.     };  

这段JS代码主要是往canvas容器中构造一个Canvas对象,并且对这个canvas对象的外观以及动画属性作了初始化。

JavaScript Code复制内容到剪贴板
  1. var Particle = function(x, y, hue){ this.x = x; this.y = y; this.coordLast = [   
  2.             {x: x, y: y},   
  3.             {x: x, y: y},   
  4.             {x: x, y: y}   
  5.         ]; this.angle = rand(0, 360); this.speed = rand(((self.partSpeed - self.partSpeedVariance) <= 0) ? 1 : self.partSpeed - self.partSpeedVariance, (self.partSpeed + self.partSpeedVariance)); this.friction = 1 - self.partFriction/100; this.gravity = self.partGravity/2; this.hue = rand(hue-self.hueVariance, hue+self.hueVariance); this.brightness = rand(50, 80); this.alpha = rand(40,100)/100; this.decay = rand(10, 50)/1000; this.wind = (rand(0, self.partWind) - (self.partWind/2))/25; this.lineWidth = self.lineWidth;   
  6.     };   
  7.   
  8.     Particle.prototype.update = function(index){ var radians = this.angle * Math.PI / 180; var vx = Math.cos(radians) * this.speed; var vy = Math.sin(radians) * this.speed + this.gravity; this.speed *= this.friction; this.coordLast[2].x = this.coordLast[1].x; this.coordLast[2].y = this.coordLast[1].y; this.coordLast[1].x = this.coordLast[0].x; this.coordLast[1].y = this.coordLast[0].y; this.coordLast[0].x = this.x; this.coordLast[0].y = this.y; this.x += vx * self.dt; this.y += vy * self.dt; this.angle += this.wind; this.alpha -= this.decay; if(!hitTest(0,0,self.cw,self.ch,this.x-this.radius, this.y-this.radius, this.radius*2, this.radius*2) || this.alpha < .05){                       
  9.             self.particles.splice(index, 1);       
  10.         }               
  11.     };   
  12.   
  13.     Particle.prototype.draw = function(){ var coordRand = (rand(1,3)-1);   
  14.         self.ctx.beginPath();                                   
  15.         self.ctx.moveTo(Math.round(this.coordLast[coordRand].x), Math.round(this.coordLast[coordRand].y));   
  16.         self.ctx.lineTo(Math.round(this.x), Math.round(this.y));   
  17.         self.ctx.closePath();                   
  18.         self.ctx.strokeStyle = 'hsla('+this.hue+', 100%, '+this.brightness+'%, '+this.alpha+')';   
  19.         self.ctx.stroke(); if(self.flickerDensity > 0){ var inverseDensity = 50 - self.flickerDensity; if(rand(0, inverseDensity) === inverseDensity){   
  20.                 self.ctx.beginPath();   
  21.                 self.ctx.arc(Math.round(this.x), Math.round(this.y), rand(this.lineWidth,this.lineWidth+3)/2, 0, Math.PI*2, false)  self.ctx.closePath(); var randAlpha = rand(50,100)/100;   
  22.                 self.ctx.fillStyle = 'hsla('+this.hue+', 100%, '+this.brightness+'%, '+randAlpha+')';   
  23.                 self.ctx.fill();   
  24.             }       
  25.         }   
  26.     };  

这段JS代码的功能是实现烟花爆炸后的小颗粒的绘制,从draw方法中可以看出,创建几个随机点,烟花颗粒即可在这个范围的随机点中散落。

JavaScript Code复制内容到剪贴板
  1. var Firework = function(startX, startY, targetX, targetY){ this.x = startX; this.y = startY; this.startX = startX; this.startY = startY; this.hitX = falsethis.hitY = falsethis.coordLast = [   
  2.             {x: startX, y: startY},   
  3.             {x: startX, y: startY},   
  4.             {x: startX, y: startY}   
  5.         ]; this.targetX = targetX; this.targetY = targetY; this.speed = self.fworkSpeed; this.angle = Math.atan2(targetY - startY, targetX - startX); this.shockwaveAngle = Math.atan2(targetY - startY, targetX - startX)+(90*(Math.PI/180)); this.acceleration = self.fworkAccel/100; this.hue = self.currentHue; this.brightness = rand(50, 80); this.alpha = rand(50,100)/100; this.lineWidth = self.lineWidth; this.targetRadius = 1;   
  6.     };   
  7.   
  8.     Firework.prototype.update = function(index){   
  9.         self.ctx.lineWidth = this.lineWidth;   
  10.   
  11.         vx = Math.cos(this.angle) * this.speed,   
  12.         vy = Math.sin(this.angle) * this.speed; this.speed *= 1 + this.acceleration; this.coordLast[2].x = this.coordLast[1].x; this.coordLast[2].y = this.coordLast[1].y; this.coordLast[1].x = this.coordLast[0].x; this.coordLast[1].y = this.coordLast[0].y; this.coordLast[0].x = this.x; this.coordLast[0].y = this.y; if(self.showTarget){ if(this.targetRadius < 8){ this.targetRadius += .25 * self.dt;   
  13.             } else { this.targetRadius = 1 * self.dt;       
  14.             }   
  15.         } if(this.startX >= this.targetX){ if(this.x + vx <= this.targetX){ this.x = this.targetX; this.hitX = true;   
  16.             } else { this.x += vx * self.dt;   
  17.             }   
  18.         } else { if(this.x + vx >= this.targetX){ this.x = this.targetX; this.hitX = true;   
  19.             } else { this.x += vx * self.dt;   
  20.             }   
  21.         } if(this.startY >= this.targetY){ if(this.y + vy <= this.targetY){ this.y = this.targetY; this.hitY = true;   
  22.             } else { this.y += vy * self.dt;   
  23.             }   
  24.         } else { if(this.y + vy >= this.targetY){ this.y = this.targetY; this.hitY = true;   
  25.             } else { this.y += vy * self.dt;   
  26.             }   
  27.         } if(this.hitX && this.hitY){ var randExplosion = rand(0, 9);   
  28.             self.createParticles(this.targetX, this.targetY, this.hue);   
  29.             self.fireworks.splice(index, 1);                       
  30.         }   
  31.     };   
  32.   
  33.     Firework.prototype.draw = function(){   
  34.         self.ctx.lineWidth = this.lineWidth; var coordRand = (rand(1,3)-1);                       
  35.         self.ctx.beginPath();                               
  36.         self.ctx.moveTo(Math.round(this.coordLast[coordRand].x), Math.round(this.coordLast[coordRand].y));   
  37.         self.ctx.lineTo(Math.round(this.x), Math.round(this.y));   
  38.         self.ctx.closePath();   
  39.         self.ctx.strokeStyle = 'hsla('+this.hue+', 100%, '+this.brightness+'%, '+this.alpha+')';   
  40.         self.ctx.stroke(); if(self.showTarget){   
  41.             self.ctx.save();   
  42.             self.ctx.beginPath();   
  43.             self.ctx.arc(Math.round(this.targetX), Math.round(this.targetY), this.targetRadius, 0, Math.PI*2, false)   
  44.             self.ctx.closePath();   
  45.             self.ctx.lineWidth = 1;   
  46.             self.ctx.stroke();   
  47.             self.ctx.restore();   
  48.         } if(self.showShockwave){   
  49.             self.ctx.save();   
  50.             self.ctx.translate(Math.round(this.x), Math.round(this.y));   
  51.             self.ctx.rotate(this.shockwaveAngle);   
  52.             self.ctx.beginPath();   
  53.             self.ctx.arc(0, 0, 1*(this.speed/5), 0, Math.PI, true);   
  54.             self.ctx.strokeStyle = 'hsla('+this.hue+', 100%, '+this.brightness+'%, '+rand(25, 60)/100+')';   
  55.             self.ctx.lineWidth = this.lineWidth;   
  56.             self.ctx.stroke();   
  57.             self.ctx.restore();   
  58.         }                                    
  59.     };  

这段JS代码是创建烟花实例的,我们也可以从draw方法中看出,当我们鼠标点击画布中的某点时,烟花发射的目的地就在那个点上。

这款HTML5 Canvas烟花效果的核心代码就是这样,谢谢阅读,希望能帮到大家,请继续关注三水点靠木,我们会努力分享更多优秀的文章。

HTML / CSS 相关文章推荐
CSS3中动画属性transform、transition和animation属性的区别
Sep 25 HTML / CSS
使用CSS3创建动态菜单效果
Jul 10 HTML / CSS
使用 CSS3 中@media 实现网页自适应的示例代码
Mar 24 HTML / CSS
HTML5实时语音通话聊天MP3压缩传输3KB每秒
Aug 28 HTML / CSS
基于HTML5超酷摄像头(HTML5 webcam)拍照功能实现代码
Dec 13 HTML / CSS
HTML5本地存储之Database Storage应用介绍
Jan 06 HTML / CSS
HTML5 通信API 跨域门槛将不再高、数据推送也不再是梦
Apr 25 HTML / CSS
HTML5调用手机摄像头拍照的实现思路及代码
Jun 15 HTML / CSS
HTML5+CSS3模仿优酷视频截图功能示例
Jan 05 HTML / CSS
CSS3常见动画的实现方式
Apr 14 HTML / CSS
CSS 新特性 contain控制页面的重绘与重排问题
Apr 30 HTML / CSS
新的CSS 伪类函数 :is() 和 :where()示例详解
Aug 05 HTML / CSS
HTML5制作3D爱心动画教程 献给女友浪漫的礼物
Nov 05 #HTML / CSS
html5 css3实例教程 一款html5和css3实现的小机器人走路动画
Oct 20 #HTML / CSS
实例教程 利用html5和css3打造一款创意404页面
Oct 20 #HTML / CSS
基于html5实现的图片墙效果
Oct 16 #HTML / CSS
html5版canvas自由拼图实例
Oct 15 #HTML / CSS
HTML5地理定位实例
Oct 15 #HTML / CSS
IE9对HTML5中部分属性不支持的原因分析
Oct 15 #HTML / CSS
You might like
在apache下限制每个虚拟主机的并发数!!!!
2006/10/09 PHP
php数组函数序列之asort() - 对数组的元素值进行升序排序,保持索引关系
2011/11/02 PHP
php文件缓存类用法实例分析
2015/04/22 PHP
php中smarty实现多模版网站的方法
2015/06/11 PHP
php unlink()函数使用教程
2018/07/12 PHP
PHP+redis实现的限制抢购防止商品超发功能详解
2019/09/19 PHP
Thinkphp框架使用list_to_tree 实现无限级分类列出所有节点示例
2020/04/04 PHP
js 模式窗口(模式对话框和非模式对话框)的使用介绍
2014/07/17 Javascript
Node.js实现的简易网页抓取功能示例
2014/12/05 Javascript
JavaScript设计模式之原型模式(Object.create与prototype)介绍
2014/12/28 Javascript
jquery实现移动端点击图片查看大图特效
2020/09/11 Javascript
JavaScript编写带旋转+线条干扰的验证码脚本实例
2016/05/30 Javascript
微信小程序 数据访问实例详解
2016/10/08 Javascript
深究AngularJS如何获取input的焦点(自定义指令)
2017/06/12 Javascript
用Vue.extend构建消息提示组件的方法实例
2017/08/08 Javascript
vue-cli3脚手架的配置及使用教程
2018/08/28 Javascript
[42:25]2018DOTA2亚洲邀请赛 4.5 淘汰赛 LGD vs Liquid 第三场
2018/04/06 DOTA
Python 数据结构之堆栈实例代码
2017/01/22 Python
教你使用python画一朵花送女朋友
2018/03/29 Python
Python3实现的字典遍历操作详解
2018/04/18 Python
python 同时运行多个程序的实例
2019/01/07 Python
解决python测试opencv时imread导致的错误问题
2019/01/26 Python
python用类实现文章敏感词的过滤方法示例
2019/10/27 Python
python-xpath获取html文档的部分内容
2020/03/06 Python
Python爬虫获取op.gg英雄联盟英雄对位胜率的源码
2021/01/29 Python
银行实习自我鉴定
2013/10/12 职场文书
企业管理培训感言
2014/01/27 职场文书
行政人事经理职位说明书
2014/03/05 职场文书
《长征》教学反思
2014/04/27 职场文书
毕业论文评语大全
2014/04/29 职场文书
环境科学专业教师求职信
2014/07/12 职场文书
“四风”问题整改措施和努力方向
2014/09/20 职场文书
2014报到证办理个人委托书
2014/10/08 职场文书
2014年公务员工作总结
2014/11/18 职场文书
优秀共青团员事迹材料
2014/12/25 职场文书
Nginx配置文件详解以及优化建议指南
2021/09/15 Servers