이 기사에서는 HTML5 Canvas에서 구현된 안전하고 환경 친화적인 무료 불꽃놀이 특수 효과를 소개합니다.
효과는 다음과 같습니다.
코드는 다음과 같습니다.
XML/HTML 코드클립보드에 콘텐츠 복사
- >
-
<html>
-
<머리>
-
<제목>캔버스 实现放烟꽃特效제목>
-
<메타 문자 집합="utf- 8">
-
<메타 http-equiv=" X-UA 호환" 콘텐츠="IE=edge">
-
<메타 이름="뷰포트" 콘텐츠="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0 ,user-scalable=no">
-
<스타일 유형="text/ css">
- html,body{height:100%;margin:0;padding:0}
- ul,li{text-indent:0;text-decoration:none;margin:0;padding:0}
- img{border:0}
- 본문{배경색:#000;색상:#999;글꼴:100%/18px helvetica, arial, sans-serif}
- 캔버스{cursor:crosshair;display:block;left:0;position:absolute;top:0;z-index:20}
- #header img{너비:100%; 높이:20%;}
- #bg img{너비:100%; 높이:80%;}
- #header,#bg{위치:고정;왼쪽:0;오른쪽:0;z-index:10}
- #header{top:0}
- #bg{위치:고정;z-색인:1;하단:0}
- 오디오{위치:고정;디스플레이:없음;하단:0;왼쪽:0;오른쪽:0;너비:100%;z-색인:5}
-
스타일>
-
머리>
-
<몸>
-
<div id="bg" >
-
<img id="bgimg" src="http://img.ivsky.com/img/tupian/pre/201508/02/yuzhou_xingkong_yu_yueliang-006 .jpg">
-
div>
-
<스크립트 src="http: //cdn.bootcss.com/jquery/2.2.0/jquery.min.js">스크립트 >
-
<스크립트>
- $(함수(){
-
var 불꽃놀이 = 기능(){
-
var self = this;
- // 产生烟꽃随机数
-
var rand = 함수(rMi, rMa){
- //按位取反运算符
- return ~~((Math.random()*(rMa-rMi 1)) rMi);
-
},hitTest = 함수(x1, y1, w1, h1, x2, y2, w2, h2){
-
반품 !(x1 w1 < x2 || x2 w2 < x1 || y1 h1 < y2 || y2 h2 < y1);
- };
- //请求动画帧
- window.requestAnimFrame=함수(){
- return window.requestAnimationFrame
- ||window.webkitRequestAnimationFrame
- ||window.mozRequestAnimationFrame
- ||window.oRequestAnimationFrame
- ||window.msRequestAnimationFrame
- ||함수(콜백){
- window.setTimeout(callback,1000/60);
- }
- }();
- self.init = 함수(){
- self.canvas = document.createElement('canvas');
- //캔버스 전체屏
- selfself.canvas.width = self.cw = $(창 ).innerWidth();
- selfself.canvas.height = self.ch = $(창 ).내부 높이();
- self.particles = [];
- self.partCount = 150;
- self.fireworks = [];
- selfself.mx = self.cw/2;
- selfself.my = self.ch/2;
- self.currentHue = 30;
- self.partSpeed = 5;
- self.partSpeedVariance = 10;
- self.partWind = 50;
- self.partFriction = 5;
- self.partGravity = 1;
- self.hueMin = 0;
- self.hueMax = 360;
- self.fworkSpeed = 4;
- self.fworkAccel = 10;
- self.hueVariance = 30;
- self.flickerDensity = 25;
- self.showShockwave = 참;
- self.showTarget = false;
- self.clearAlpha = 25;
- $(document.body).append(self.canvas);
- selfself.ctx = self.canvas.getContext('2d');
- self.ctx.lineCap = '둥근';
- self.ctx.lineJoin = '둥근';
- self.lineWidth = 1;
- self.bindEvents();
- self.canvasLoop();
- self.canvas.onselectstart = 기능() {
- false를 반환합니다.
- };
- };
- // 创建粒子
- self.createParticles = 함수(x,y, hue){
- var 카운트다운 = self.partCount;
- 동안(카운트다운--){
- var newParticle = {
- x: x,
- y: y,
- coordLast: [
- {x: x, y: y},
- {x: x, y: y},
- {x: x, y: y}
- ],
- 각도: rand(0, 360),
- 속도: rand(((self.partSpeed - self.partSpeedVariance) <= 0) ? 1 : self.partSpeed - self.partSpeedVariance,(self .partSpeed self.partSpeedVariance)),
- 마찰: 1 - self.partFriction/100,
- 중력: self.partGravity/2,
- hue: rand(hue-self.hueVariance, hue self.hueVariance),
- 밝기: rand(50, 80),
- 알파: rand(40,100)/100,
- 감소: rand(10, 50)/1000,
- 바람: (rand(0, self.partWind) - (self.partWind/2))/25,
- lineWidth: self.lineWidth
- };
- self.particles.push(newParticle);
- }
- };
- // 更新粒子
- self.updateParticles = 함수(){
- var i = self.particles.length;
- 동안(i--){
- var p = self.particles[i];
- var 라디안 = p.angle * Math.PI / 180;
- var vx = 수학.cos(라디안) * p.speed;
- var vy = Math.sin(라디안) * p.speed;
- p.speed *= p.friction;
- p.coordLast[2].x = p.coordLast[1].x;
- p.coordLast[2].y = p.coordLast[1].y;
- p.coordLast[1].x = p.coordLast[0].x;
- p.coordLast[1].y = p.coordLast[0].y;
- p.coordLast[0].x = p.x;
- p.coordLast[0].y = p.y;
- p.x = vx;
- p.y = vy;
- p.y = p.gravity;
- p.angle = p.wind;
- p.alpha -= p.decay;
- if(!hitTest(0,0,self.cw,self.ch,p.x-p.radius, p.y-p.radius, p.radius*2, p.radius*2) || p .alpha < .05){
- self.particles.splice(i, 1);
- }
- };
- };
- // 绘粒子
- self.drawParticles = 함수(){
- var i = self.particles.length;
- 동안(i--){
- var p = self.particles[i];
- var coordRand = (rand(1,3)-1);
- self.ctx.beginPath();
- self.ctx.moveTo(Math.round(p.coordLast[coordRand].x), Math.round(p.coordLast[coordRand].y));
- self.ctx.lineTo(Math.round(p.x), Math.round(p.y));
- self.ctx.closePath();
- self.ctx.StrokeStyle = 'hsla(' p.hue ', 100%, ' p .brightness '%, ' p.alpha ')';
- self.ctx.Stroke();
- if(self.flickerDensity > 0){
-
var inverseDensity = 50 - self.flickerDensity;
- if(rand(0, inverseDensity) === inverseDensity){
- self.ctx.beginPath();
- self.ctx.arc(Math.round(p.x), Math.round(p.y), rand(p.lineWidth,p.lineWidth 3)/2, 0, Math.PI*2, false)
- self.ctx.closePath();
-
var randrandAlpha = rand(50,100)/100;
-
self.ctx.fillStyle = 'hsla(' p.hue ', 100%, ' p .brightness '%, ' randAlpha ')';
- self.ctx.fill();
- }
- }
- };
- };
- // 创建烟꽃
-
self.createFireworks = 함수(startX, startY, targetX, targetY){
-
var newFirework = {
- x: startX,
- y: startY,
- startX: startX,
- startY: startY,
- hitX: false,
- hitY: false,
- coordLast: [
- {x: startX, y: startY},
- {x: startX, y: startY},
- {x: startX, y: startY}
- ],
- targetX: targetX,
- targetY: targetY,
- 속도: self.fworkSpeed,
- 각도: Math.atan2(targetY - startY, targetX - startX),
- shockwaveAngle: Math.atan2(targetY - startY, targetX - startX) (90*(Math.PI/180)),
- 가속: self.fworkAccel/100,
- hue: self.currentHue,
- 밝기: rand(50, 80),
- 알파: rand(50,100)/100,
- lineWidth: self.lineWidth
- };
- self.fireworks.push(newFirework);
- };
- // 更新烟꽃
-
self.updateFireworks = 기능(){
-
var i = self.fireworks.length;
- 동안(i--){
-
var f = self.fireworks[i];
-
self.ctx.lineWidth = f.lineWidth;
-
vx = 수학.cos(f.angle) * f.speed,
-
vy = 수학.sin(f.angle) * f.speed;
- f.속도 *= 1 f.가속;
-
f.coordLast[2].x = f.coordLast[1].x;
-
f.coordLast[2].y = f.coordLast[1].y;
-
f.coordLast[1].x = f.coordLast[0].x;
-
f.coordLast[1].y = f.coordLast[0].y;
-
f.coordLast[0].x = f.x;
-
f.coordLast[0].y = f.y;
-
if(f.startX >= f.targetX){
-
if(f.x vx <= f.targetX){
- ff.x = f.targetX;
- f.hitX = 참;
- } else {
- f.x = vx;
- }
- } 그렇지 않으면 {
- if(f.x vx >= f.targetX){
-
ff.x = f.targetX;
-
f.hitX = 참;
- } else {
- f.x = vx;
- }
- }
-
if(f.startY >= f.targetY){
-
if(f.y vy <= f.targetY){
- ff.y = f.targetY;
- f.hitY = 참;
- } else {
- f.y = vy;
- }
- } 그렇지 않으면 {
- if(f.y vy >= f.targetY){
-
ff.y = f.targetY;
-
f.hitY = 참;
- } else {
- f.y = vy;
- }
- }
- if(f.hitX && f.hitY){
- self.createParticles(f.targetX, f.targetY, f.hue);
- self.fireworks.splice(i, 1);
- }
- };
- };
- // 绘烟꽃
-
self.drawFireworks = 기능(){
-
var i = self.fireworks.length;
-
self.ctx.globalCompositeOperation = '가벼움';
- 동안(i--){
-
var f = self.fireworks[i];
-
self.ctx.lineWidth = f.lineWidth;
-
var coordRand = (rand(1,3)-1);
- self.ctx.beginPath();
- self.ctx.moveTo(Math.round(f.coordLast[coordRand].x), Math.round(f.coordLast[coordRand].y));
- self.ctx.lineTo(Math.round(f.x), Math.round(f.y));
- self.ctx.closePath();
-
self.ctx.StrokeStyle = 'hsla(' f.hue ', 100%, ' f .밝기 '%, ' f.alpha ')';
- self.ctx.Stroke();
- if(self.showTarget){
- self.ctx.save();
- self.ctx.beginPath();
-
self.ctx.arc(Math.round(f.targetX), Math.round(f.targetY), rand(1,8), 0, Math.PI*2, false)
- self.ctx.closePath();
-
self.ctx.lineWidth = 1;
- self.ctx.Stroke();
- self.ctx.restore();
- }
- if(self.showShockwave){
- self.ctx.save();
- self.ctx.translate(Math.round(f.x), Math.round(f.y));
- self.ctx.rotate(f.shockwaveAngle);
- self.ctx.beginPath();
- self.ctx.arc(0, 0, 1*(f.speed/5), 0, Math.PI, true);
-
self.ctx.StrokeStyle = 'hsla(' f.hue ', 100%, ' f .brightness '%, ' rand(25, 60)/100 ')';
-
self.ctx.lineWidth = f.lineWidth;
- self.ctx.Stroke();
- self.ctx.restore();
- }
- };
- };
- // 绑定事件
-
self.bindEvents = 함수(){
- $(window).on('resize', function(){
- clearTimeout(self.timeout);
-
self.timeout = setTimeout(function() {
-
selfself.canvas.width = self.cw = $(window ).innerWidth();
-
selfself.canvas.height = self.ch = $(window ).내부 높이();
-
self.ctx.lineCap = '둥근';
-
self.ctx.lineJoin = '둥근';
- }, 100);
- });
- $(self.canvas).on('mousedown', function(e){
-
self.mx = e.pageX - self.canvas.offsetLeft;
-
self.my = e.pageY - self.canvas.offsetTop;
-
self.currentHue = rand(self.hueMin, self.hueMax);
- self.createFireworks(self.cw/2, self.ch, self.mx, self.my);
- $(self.canvas).on('mousemove.fireworks', function(e){
-
self.mx = e.pageX - self.canvas.offsetLeft;
-
self.my = e.pageY - self.canvas.offsetTop;
-
self.currentHue = rand(self.hueMin, self.hueMax);
- self.createFireworks(self.cw/2, self.ch, self.mx, self.my);
- });
- });
- $(self.canvas).on('mouseup', function(e){
- $(self.canvas).off('mousemove.fireworks');
- });
- };
-
self.clear = 함수(){
-
self.particles = [];
-
self.fireworks = [];
- self.ctx.clearRect(0, 0, self.cw, self.ch);
- };
-
self.canvasLoop = 기능(){
- requestAnimFrame(self.canvasLoop, self.canvas);
-
self.ctx.globalCompositeOperation = 'destination-out';
-
self.ctx.fillStyle = 'rgba(0,0,0,' self.clearAlpha/ 100')';
- self.ctx.fillRect(0,0,self.cw,self.ch);
- self.updateFireworks();
- self.updateParticles();
- self.drawFireworks();
- self.drawParticles();
- };
- self.init();
- }
-
var fworks = new Fireworks();
- $('#info-toggle').on('click', function(e){
- $('#info-inner').stop(false, true).slideToggle(100);
- e.preventDefault();
- });
- });
-
스크립트>
-
<캔버스 너비="1400" 높이="449">캔버스>
-
본체>
-
html>
是不是被HTML5는 매우 큰 의미를 갖습니다.