首页 > 其他分享 >烟花特效

烟花特效

时间:2022-11-21 14:37:41浏览次数:49  
标签:function 特效 canvas const random 烟花 var Math

1、

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        
<meta charset="utf-8">
<title>3D烟花</title>
 
<style>
html,body{
    margin:0px;
    width:100%;
    height:100%;
    overflow:hidden;
    background:#000;
}
 
#canvas{
    width:100%;
    height:100%;
}
</style>
</head>
    
    <body>
<canvas id="canvas" width="825" height="631"></canvas><script>
function initVars(){
 
    pi=Math.PI;
    ctx=canvas.getContext("2d");
    canvas.width=canvas.clientWidth;
    canvas.height=canvas.clientHeight;
    cx=canvas.width/2;
    cy=canvas.height/2;
    playerZ=-25;
    playerX=playerY=playerVX=playerVY=playerVZ=pitch=yaw=pitchV=yawV=0;
    scale=600;
    seedTimer=0;seedInterval=5,seedLife=100;gravity=.02;
    seeds=new Array();
    sparkPics=new Array();
    s="https://cantelope.org/NYE/";
    for(i=1;i<=10;++i){
        sparkPic=new Image();
        sparkPic.src=s+"spark"+i+".png";
        sparkPics.push(sparkPic);
    }
    sparks=new Array();
    pow1=new Audio(s+"pow1.ogg");
    pow2=new Audio(s+"pow2.ogg");
    pow3=new Audio(s+"pow3.ogg");
    pow4=new Audio(s+"pow4.ogg");
    frames = 0;
}
 
function rasterizePoint(x,y,z){
 
    var p,d;
    x-=playerX;
    y-=playerY;
    z-=playerZ;
    p=Math.atan2(x,z);
    d=Math.sqrt(x*x+z*z);
    x=Math.sin(p-yaw)*d;
    z=Math.cos(p-yaw)*d;
    p=Math.atan2(y,z);
    d=Math.sqrt(y*y+z*z);
    y=Math.sin(p-pitch)*d;
    z=Math.cos(p-pitch)*d;
    var rx1=-1000,ry1=1,rx2=1000,ry2=1,rx3=0,ry3=0,rx4=x,ry4=z,uc=(ry4-ry3)*(rx2-rx1)-(rx4-rx3)*(ry2-ry1);
    if(!uc) return {x:0,y:0,d:-1};
    var ua=((rx4-rx3)*(ry1-ry3)-(ry4-ry3)*(rx1-rx3))/uc;
    var ub=((rx2-rx1)*(ry1-ry3)-(ry2-ry1)*(rx1-rx3))/uc;
    if(!z)z=.000000001;
    if(ua>0&&ua<1&&ub>0&&ub<1){
        return {
            x:cx+(rx1+ua*(rx2-rx1))*scale,
            y:cy+y/z*scale,
            d:Math.sqrt(x*x+y*y+z*z)
        };
    }else{
        return {
            x:cx+(rx1+ua*(rx2-rx1))*scale,
            y:cy+y/z*scale,
            d:-1
        };
    }
}
 
function spawnSeed(){
    
    seed=new Object();
    seed.x=-50+Math.random()*100;
    seed.y=25;
    seed.z=-50+Math.random()*100;
    seed.vx=.1-Math.random()*.2;
    seed.vy=-1.5;//*(1+Math.random()/2);
    seed.vz=.1-Math.random()*.2;
    seed.born=frames;
    seeds.push(seed);
}
 
function splode(x,y,z){
    
    t=5+parseInt(Math.random()*150);
    sparkV=1+Math.random()*2.5;
    type=parseInt(Math.random()*3);
    switch(type){
        case 0:
            pic1=parseInt(Math.random()*10);
            break;
        case 1:
            pic1=parseInt(Math.random()*10);
            do{ pic2=parseInt(Math.random()*10); }while(pic2==pic1);
            break;
        case 2:
            pic1=parseInt(Math.random()*10);
            do{ pic2=parseInt(Math.random()*10); }while(pic2==pic1);
            do{ pic3=parseInt(Math.random()*10); }while(pic3==pic1 || pic3==pic2);
            break;
    }
    for(m=1;m<t;++m){
        spark=new Object();
        spark.x=x; spark.y=y; spark.z=z;
        p1=pi*2*Math.random();
        p2=pi*Math.random();
        v=sparkV*(1+Math.random()/6)
        spark.vx=Math.sin(p1)*Math.sin(p2)*v;
        spark.vz=Math.cos(p1)*Math.sin(p2)*v;
        spark.vy=Math.cos(p2)*v;
        switch(type){
            case 0: spark.img=sparkPics[pic1]; break;
            case 1:
                spark.img=sparkPics[parseInt(Math.random()*2)?pic1:pic2];
                break;
            case 2:
                switch(parseInt(Math.random()*3)){
                    case 0: spark.img=sparkPics[pic1]; break;
                    case 1: spark.img=sparkPics[pic2]; break;
                    case 2: spark.img=sparkPics[pic3]; break;
                }
                break;
        }
        spark.radius=25+Math.random()*50;
        spark.alpha=1;
        spark.trail=new Array();
        sparks.push(spark);
    }
    switch(parseInt(Math.random()*4)){
        case 0:    pow=new Audio(s+"pow1.ogg"); break;
        case 1:    pow=new Audio(s+"pow2.ogg"); break;
        case 2:    pow=new Audio(s+"pow3.ogg"); break;
        case 3:    pow=new Audio(s+"pow4.ogg"); break;
    }
    d=Math.sqrt((x-playerX)*(x-playerX)+(y-playerY)*(y-playerY)+(z-playerZ)*(z-playerZ));
    pow.volume=1.5/(1+d/10);
    pow.play();
}
 
function doLogic(){
    
    if(seedTimer<frames){
        seedTimer=frames+seedInterval*Math.random()*10;
        spawnSeed();
    }
    for(i=0;i<seeds.length;++i){
        seeds[i].vy+=gravity;
        seeds[i].x+=seeds[i].vx;
        seeds[i].y+=seeds[i].vy;
        seeds[i].z+=seeds[i].vz;
        if(frames-seeds[i].born>seedLife){
            splode(seeds[i].x,seeds[i].y,seeds[i].z);
            seeds.splice(i,1);
        }
    }
    for(i=0;i<sparks.length;++i){
        if(sparks[i].alpha>0 && sparks[i].radius>5){
            sparks[i].alpha-=.01;
            sparks[i].radius/=1.02;
            sparks[i].vy+=gravity;
            point=new Object();
            point.x=sparks[i].x;
            point.y=sparks[i].y;
            point.z=sparks[i].z;
            if(sparks[i].trail.length){
                x=sparks[i].trail[sparks[i].trail.length-1].x;
                y=sparks[i].trail[sparks[i].trail.length-1].y;
                z=sparks[i].trail[sparks[i].trail.length-1].z;
                d=((point.x-x)*(point.x-x)+(point.y-y)*(point.y-y)+(point.z-z)*(point.z-z));
                if(d>9){
                    sparks[i].trail.push(point);
                }
            }else{
                sparks[i].trail.push(point);
            }
            if(sparks[i].trail.length>5)sparks[i].trail.splice(0,1);                
            sparks[i].x+=sparks[i].vx;
            sparks[i].y+=sparks[i].vy;
            sparks[i].z+=sparks[i].vz;
            sparks[i].vx/=1.075;
            sparks[i].vy/=1.075;
            sparks[i].vz/=1.075;
        }else{
            sparks.splice(i,1);
        }
    }
    p=Math.atan2(playerX,playerZ);
    d=Math.sqrt(playerX*playerX+playerZ*playerZ);
    d+=Math.sin(frames/80)/1.25;
    t=Math.sin(frames/200)/40;
    playerX=Math.sin(p+t)*d;
    playerZ=Math.cos(p+t)*d;
    yaw=pi+p+t;
}
 
function rgb(col){
    
    var r = parseInt((.5+Math.sin(col)*.5)*16);
    var g = parseInt((.5+Math.cos(col)*.5)*16);
    var b = parseInt((.5-Math.sin(col)*.5)*16);
    return "#"+r.toString(16)+g.toString(16)+b.toString(16);
}
 
function draw(){
    
    ctx.clearRect(0,0,cx*2,cy*2);
    
    ctx.fillStyle="#ff8";
    for(i=-100;i<100;i+=3){
        for(j=-100;j<100;j+=4){
            x=i;z=j;y=25;
            point=rasterizePoint(x,y,z);
            if(point.d!=-1){
                size=250/(1+point.d);
                d = Math.sqrt(x * x + z * z);
                a = 0.75 - Math.pow(d / 100, 6) * 0.75;
                if(a>0){
                    ctx.globalAlpha = a;
                    ctx.fillRect(point.x-size/2,point.y-size/2,size,size);                
                }
            }
        }
    }
    ctx.globalAlpha=1;
    for(i=0;i<seeds.length;++i){
        point=rasterizePoint(seeds[i].x,seeds[i].y,seeds[i].z);
        if(point.d!=-1){
            size=200/(1+point.d);
            ctx.fillRect(point.x-size/2,point.y-size/2,size,size);
        }
    }
    point1=new Object();
    for(i=0;i<sparks.length;++i){
        point=rasterizePoint(sparks[i].x,sparks[i].y,sparks[i].z);
        if(point.d!=-1){
            size=sparks[i].radius*200/(1+point.d);
            if(sparks[i].alpha<0)sparks[i].alpha=0;
            if(sparks[i].trail.length){
                point1.x=point.x;
                point1.y=point.y;
                switch(sparks[i].img){
                    case sparkPics[0]:ctx.strokeStyle="#f84";break;
                    case sparkPics[1]:ctx.strokeStyle="#84f";break;
                    case sparkPics[2]:ctx.strokeStyle="#8ff";break;
                    case sparkPics[3]:ctx.strokeStyle="#fff";break;
                    case sparkPics[4]:ctx.strokeStyle="#4f8";break;
                    case sparkPics[5]:ctx.strokeStyle="#f44";break;
                    case sparkPics[6]:ctx.strokeStyle="#f84";break;
                    case sparkPics[7]:ctx.strokeStyle="#84f";break;
                    case sparkPics[8]:ctx.strokeStyle="#fff";break;
                    case sparkPics[9]:ctx.strokeStyle="#44f";break;
                }
                for(j=sparks[i].trail.length-1;j>=0;--j){
                    point2=rasterizePoint(sparks[i].trail[j].x,sparks[i].trail[j].y,sparks[i].trail[j].z);
                    if(point2.d!=-1){
                        ctx.globalAlpha=j/sparks[i].trail.length*sparks[i].alpha/2;
                        ctx.beginPath();
                        ctx.moveTo(point1.x,point1.y);
                        ctx.lineWidth=1+sparks[i].radius*10/(sparks[i].trail.length-j)/(1+point2.d);
                        ctx.lineTo(point2.x,point2.y);
                        ctx.stroke();
                        point1.x=point2.x;
                        point1.y=point2.y;
                    }
                }
            }
            ctx.globalAlpha=sparks[i].alpha;
            ctx.drawImage(sparks[i].img,point.x-size/2,point.y-size/2,size,size);
        }
    }
}
 
function frame(){
 
    if(frames>100000){
        seedTimer=0;
        frames=0;
    }
    frames++;
    draw();
    doLogic();
    requestAnimationFrame(frame);
}
 
window.addEventListener("resize",()=>{
    canvas.width=canvas.clientWidth;
    canvas.height=canvas.clientHeight;
    cx=canvas.width/2;
    cy=canvas.height/2;
});
 
initVars();
frame();</script>
 
 
</body>
</html>

2、

 

 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head>
  <meta charset="utf-8" /> 
<meta http-equiv="Content-Type" content="text/html; charset=gbk" /> <title>JavaScript烟花</title> 
<script type="text/javascript"> 
var showcoo = function(){ 
 this.size = 40; 
 this.speed = 0.1; 
 this.rise(); 
}
 showcoo.prototype = { 
 color:function(){  
 var c = ['0','3','6','9','c','f'];  
 var t = [c[Math.floor(Math.random()*100)%6],'0','f'];  
 t.sort(function(){return Math.random()>0.5?-1:1;});  
 return '#'+t.join(''); 
 }, 
 aheight:function(){ 
  var h = document.documentElement.clientHeight; 
  return Math.abs(Math.floor(Math.random()*h-200))+201; 
 }, 
 firecracker:function(){  
 var b = document.createElement('div');  
 var w = document.body.clientWidth;  
 b.style.color = this.color();  
 b.style.position = 'absolute';  
 b.style.bottom = 0;  
 b.style.left = Math.floor(Math.random()*w)+1+'px';  
 document.body.appendChild(b);  
 return b;  
}, 
 rise:function(){ 
  var o = this.firecracker(); 
  var n = this.aheight(); 
  var speed = this.speed; 
  var e = this.expl; 
  var s = this.size; 
  var k = n;  
  var m = function(){  
  o.style.bottom = parseFloat(o.style.bottom)+k*speed+'px';  
  k-=k*speed;  
  if(k<2){  
   clearInterval(clear);  
   e(o,n,s,speed);  
  }  
 }  
 o.innerHTML = '*';  
 if(parseInt(o.style.bottom)<n){  
  var clear = setInterval(m,20); 
  } 
 }, 
 expl:function(o,n,s,speed){ 
  var R = n/3; 
  var Ri = n/6; 
  var r = 0; 
  var ri = 0; 
  for(var i=0;i<s;i++){ 
   var span = document.createElement('span'); 
   var p = document.createElement('p'); 
   span.style.position = 'absolute'; 
   span.style.left = 0; 
   span.style.top = 0; 
   span.innerHTML = '*'; 
   p.style.position = 'absolute'; 
   p.style.left = 0; 
   p.style.top = 0; 
   p.innerHTML = '+'; 
   o.appendChild(span); 
   o.appendChild(p); 
  } 
  function spr(){ 
   r += R*speed; 
   ri+= Ri*speed/2; 
   sp = o.getElementsByTagName('span'); 
   p = o.getElementsByTagName('p'); 
   for(var i=0; i<sp.length;i++){ 
    sp[i].style.left=r*Math.cos(360/s*i)+'px'; 
    sp[i].style.top=r*Math.sin(360/s*i)+'px'; 
    p[i].style.left=ri*Math.cos(360/s*i)+'px'; 
    p[i].style.top=ri*Math.sin(360/s*i)+'px'; 
   } 
   R-=R*speed; 
   if(R<2){ 
    clearInterval(clearI); 
    o.parentNode.removeChild(o);  
  }  
 }  
 var clearI = setInterval(spr,20);
  }
 }
 window.onload = function(){
  function happyNewYear(){
   new showcoo(); 
 } 
 setInterval(happyNewYear,400); 
} 
</script> 
<style type="text/css">
  .aa
  {
   font: "微软雅黑";
   font-size: 30px;
   color: gold;   
   text-align: center;  
   } 
</style> 
</head> 
<body style="background:#000;font:12px Arial">
  <p class="aa">新年快乐</p>
     <img src="img/qq.jpg"style="margin: 300px 0px 0px 560px;" />
    <audio src="audio/"></audio> 
</body> 
</html>

3、

 

 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head>
  <meta charset="utf-8" /> 
<meta http-equiv="Content-Type" content="text/html; charset=gbk" /> <title>JavaScript烟花</title> 
<script type="text/javascript"> 
var showcoo = function(){ 
 this.size = 40; 
 this.speed = 0.1; 
 this.rise(); 
}
 showcoo.prototype = { 
 color:function(){  
 var c = ['0','3','6','9','c','f'];  
 var t = [c[Math.floor(Math.random()*100)%6],'0','f'];  
 t.sort(function(){return Math.random()>0.5?-1:1;});  
 return '#'+t.join(''); 
 }, 
 aheight:function(){ 
  var h = document.documentElement.clientHeight; 
  return Math.abs(Math.floor(Math.random()*h-200))+201; 
 }, 
 firecracker:function(){  
 var b = document.createElement('div');  
 var w = document.body.clientWidth;  
 b.style.color = this.color();  
 b.style.position = 'absolute';  
 b.style.bottom = 0;  
 b.style.left = Math.floor(Math.random()*w)+1+'px';  
 document.body.appendChild(b);  
 return b;  
}, 
 rise:function(){ 
  var o = this.firecracker(); 
  var n = this.aheight(); 
  var speed = this.speed; 
  var e = this.expl; 
  var s = this.size; 
  var k = n;  
  var m = function(){  
  o.style.bottom = parseFloat(o.style.bottom)+k*speed+'px';  
  k-=k*speed;  
  if(k<2){  
   clearInterval(clear);  
   e(o,n,s,speed);  
  }  
 }  
 o.innerHTML = '*';  
 if(parseInt(o.style.bottom)<n){  
  var clear = setInterval(m,20); 
  } 
 }, 
 expl:function(o,n,s,speed){ 
  var R = n/3; 
  var Ri = n/6; 
  var r = 0; 
  var ri = 0; 
  for(var i=0;i<s;i++){ 
   var span = document.createElement('span'); 
   var p = document.createElement('p'); 
   span.style.position = 'absolute'; 
   span.style.left = 0; 
   span.style.top = 0; 
   span.innerHTML = '*'; 
   p.style.position = 'absolute'; 
   p.style.left = 0; 
   p.style.top = 0; 
   p.innerHTML = '+'; 
   o.appendChild(span); 
   o.appendChild(p); 
  } 
  function spr(){ 
   r += R*speed; 
   ri+= Ri*speed/2; 
   sp = o.getElementsByTagName('span'); 
   p = o.getElementsByTagName('p'); 
   for(var i=0; i<sp.length;i++){ 
    sp[i].style.left=r*Math.cos(360/s*i)+'px'; 
    sp[i].style.top=r*Math.sin(360/s*i)+'px'; 
    p[i].style.left=ri*Math.cos(360/s*i)+'px'; 
    p[i].style.top=ri*Math.sin(360/s*i)+'px'; 
   } 
   R-=R*speed; 
   if(R<2){ 
    clearInterval(clearI); 
    o.parentNode.removeChild(o);  
  }  
 }  
 var clearI = setInterval(spr,20);
  }
 }
 window.onload = function(){
  function happyNewYear(){
   new showcoo(); 
 } 
 setInterval(happyNewYear,400); 
} 
</script> 
<style type="text/css">
  .aa
  {
   font: "微软雅黑";
   font-size: 30px;
   color: gold;   
   text-align: center;  
   } 
</style> 
</head> 
<body style="background:#000;font:12px Arial">
  <p class="aa">新年快乐</p>
     <img src="img/qq.jpg"style="margin: 300px 0px 0px 560px;" />
    <audio src="audio/"></audio> 
</body> 
</html>

4、

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            body {
              background-image: linear-gradient(6deg, #214, #000);
              background-size: 100% 100%;overflow: hidden
            }
            
            canvas { display: block; }
        </style>
    </head>
    <body>
        <div></div>
        <script type="text/javascript">
            class Vector2 {
              constructor(x = 0, y = 0) {
                this.x = x;
                this.y = y;
              }
            
              add(v) {
                this.x += v.x;
                this.y += v.y;
                return this;
              }
            
              multiplyScalar(s) {
                this.x *= s;
                this.y *= s;
                return this;
              }
            
              clone() {
                return new Vector2(this.x, this.y);
              }}
            
            
            class Time {
              constructor() {
                const now = Time.now();
            
                this.delta = 0;
                this.elapsed = 0;
                this.start = now;
                this.previous = now;
              }
            
              update() {
                const now = Time.now();
            
                this.delta = now - this.previous;
                this.elapsed = now - this.start;
                this.previous = now;
              }
            
              static now() {
                return Date.now() / 1000;
              }}
            
            
            class Particle {
              constructor(position, velocity = new Vector2(), color = 'white', radius = 1, lifetime = 1, mass = 1) {
                this.position = position;
                this.velocity = velocity;
                this.color = color;
                this.radius = radius;
                this.lifetime = lifetime;
                this.mass = mass;
            
                this.isInCanvas = true;
                this.createdOn = Time.now();
              }
            
              update(time) {
                if (!this.getRemainingLifetime()) {
                  return;
                }
            
                this.velocity.add(Particle.GRAVITATION.clone().multiplyScalar(this.mass));
                this.position.add(this.velocity.clone().multiplyScalar(time.delta));
              }
            
              render(canvas, context) {
                const remainingLifetime = this.getRemainingLifetime();
            
                if (!remainingLifetime) return;
            
                const radius = this.radius * remainingLifetime;
            
                context.globalAlpha = remainingLifetime;
                context.globalCompositeOperation = 'lighter';
                context.fillStyle = this.color;
            
                context.beginPath();
                context.arc(this.position.x, this.position.y, radius, 0, Math.PI * 2);
                context.fill();
              }
            
              getRemainingLifetime() {
                const elapsedLifetime = Time.now() - this.createdOn;
                return Math.max(0, this.lifetime - elapsedLifetime) / this.lifetime;
              }}
            
            
            Particle.GRAVITATION = new Vector2(0, 9.81);
            
            class Trail extends Particle {
              constructor(childFactory, position, velocity = new Vector2(), lifetime = 1, mass = 1) {
                super(position, velocity);
            
                this.childFactory = childFactory;
                this.children = [];
                this.lifetime = lifetime;
                this.mass = mass;
            
                this.isAlive = true;
              }
            
              update(time) {
                super.update(time);
            
                // Add a new child on every frame
                if (this.isAlive && this.getRemainingLifetime()) {
                  this.children.push(this.childFactory(this));
                }
            
                // Remove particles that are dead
                this.children = this.children.filter(function (child) {
                  if (child instanceof Trail) {
                    return child.isAlive;
                  }
            
                  return child.getRemainingLifetime();
                });
            
                // Kill trail if all particles fade away
                if (!this.children.length) {
                  this.isAlive = false;
                }
            
                // Update particles
                this.children.forEach(function (child) {
                  child.update(time);
                });
              }
            
              render(canvas, context) {
                // Render all children
                this.children.forEach(function (child) {
                  child.render(canvas, context);
                });
              }}
            
            
            class Rocket extends Trail {
              constructor(childFactory, explosionFactory, position, velocity = new Vector2()) {
                super(childFactory, position, velocity);
            
                this.explosionFactory = explosionFactory;
                this.lifetime = 10;
              }
            
              update(time) {
                if (this.getRemainingLifetime() && this.velocity.y > 0) {
                  this.explosionFactory(this);
                  this.lifetime = 0;
                }
            
                super.update(time);
              }}
            
            
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            const time = new Time();
            let rockets = [];
            
            const getTrustParticleFactory = function (baseHue) {
              function getColor() {
                const hue = Math.floor(Math.random() * 15 + 30);
                return `hsl(${hue}, 100%, 75%`;
              }
            
              return function (parent) {
                const position = this.position.clone();
                const velocity = this.velocity.clone().multiplyScalar(-.1);
                velocity.x += (Math.random() - .5) * 8;
                const color = getColor();
                const radius = 1 + Math.random();
                const lifetime = .5 + Math.random() * .5;
                const mass = .01;
            
                return new Particle(position, velocity, color, radius, lifetime, mass);
              };
            };
            
            const getExplosionFactory = function (baseHue) {
              function getColor() {
                const hue = Math.floor(baseHue + Math.random() * 15) % 360;
                const lightness = Math.floor(Math.pow(Math.random(), 2) * 50 + 50);
                return `hsl(${hue}, 100%, ${lightness}%`;
              }
            
              function getChildFactory() {
                return function (parent) {
                  const direction = Math.random() * Math.PI * 2;
                  const force = 8;
                  const velocity = new Vector2(Math.cos(direction) * force, Math.sin(direction) * force);
                  const color = getColor();
                  const radius = 1 + Math.random();
                  const lifetime = 1;
                  const mass = .1;
            
                  return new Particle(parent.position.clone(), velocity, color, radius, lifetime, mass);
                };
              }
            
              function getTrail(position) {
                const direction = Math.random() * Math.PI * 2;
                const force = Math.random() * 128;
                const velocity = new Vector2(Math.cos(direction) * force, Math.sin(direction) * force);
                const lifetime = .5 + Math.random();
                const mass = .075;
            
                return new Trail(getChildFactory(), position, velocity, lifetime, mass);
              }
            
              return function (parent) {
                let trails = 32;
                while (trails--) {
                  parent.children.push(getTrail(parent.position.clone()));
                }
              };
            };
            
            const addRocket = function () {
              const trustParticleFactory = getTrustParticleFactory();
              const explosionFactory = getExplosionFactory(Math.random() * 360);
            
              const position = new Vector2(Math.random() * canvas.width, canvas.height);
              const thrust = window.innerHeight * .75;
              const angle = Math.PI / -2 + (Math.random() - .5) * Math.PI / 8;
              const velocity = new Vector2(Math.cos(angle) * thrust, Math.sin(angle) * thrust);
              const lifetime = 3;
            
              rockets.push(new Rocket(trustParticleFactory, explosionFactory, position, velocity, lifetime));
            
              rockets = rockets.filter(function (rocket) {
                return rocket.isAlive;
              });
            };
            
            const render = function () {
              requestAnimationFrame(render);
            
              time.update();
              context.clearRect(0, 0, canvas.width, canvas.height);
            
              rockets.forEach(function (rocket) {
                rocket.update(time);
                rocket.render(canvas, context);
              });
            };
            
            const resize = function () {
              canvas.height = window.innerHeight;
              canvas.width = window.innerWidth;
            };
            
            canvas.onclick = addRocket;
            document.body.appendChild(canvas);
            
            window.onresize = resize;
            resize();
            
            setInterval(addRocket, 2000);
            render();
        </script>
    </body>
</html>

 5、指哪打哪哩

 

 

<!DOCTYPE html>
<html dir="ltr" lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>带交互功能的HTML5+JS烟花特效</title> 
<style>
/* basic styles for black background and crosshair cursor */
body {
    background: #000;
    margin: 0;
}

canvas {
    cursor: crosshair;
    display: block;
}
</style>
</head>
<canvas id="canvas">Canvas is not supported in your browser.</canvas>
<script>
// when animating on canvas, it is best to use requestAnimationFrame instead of setTimeout or setInterval
// not supported in all browsers though and sometimes needs a prefix, so we need a shim
window.requestAnimFrame = ( function() {
    return window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                function( callback ) {
                    window.setTimeout( callback, 1000 / 60 );
                };
})();

// now we will setup our basic variables for the demo
var canvas = document.getElementById( 'canvas' ),
        ctx = canvas.getContext( '2d' ),
        // full screen dimensions
        cw = window.innerWidth,
        ch = window.innerHeight,
        // firework collection
        fireworks = [],
        // particle collection
        particles = [],
        // starting hue
        hue = 120,
        // when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop ticks
        limiterTotal = 5,
        limiterTick = 0,
        // this will time the auto launches of fireworks, one launch per 80 loop ticks
        timerTotal = 80,
        timerTick = 0,
        mousedown = false,
        // mouse x coordinate,
        mx,
        // mouse y coordinate
        my;
        
// set canvas dimensions
canvas.width = cw;
canvas.height = ch;

// now we are going to setup our function placeholders for the entire demo

// get a random number within a range
function random( min, max ) {
    return Math.random() * ( max - min ) + min;
}

// calculate the distance between two points
function calculateDistance( p1x, p1y, p2x, p2y ) {
    var xDistance = p1x - p2x,
            yDistance = p1y - p2y;
    return Math.sqrt( Math.pow( xDistance, 2 ) + Math.pow( yDistance, 2 ) );
}

// create firework
function Firework( sx, sy, tx, ty ) {
    // actual coordinates
    this.x = sx;
    this.y = sy;
    // starting coordinates
    this.sx = sx;
    this.sy = sy;
    // target coordinates
    this.tx = tx;
    this.ty = ty;
    // distance from starting point to target
    this.distanceToTarget = calculateDistance( sx, sy, tx, ty );
    this.distanceTraveled = 0;
    // track the past coordinates of each firework to create a trail effect, increase the coordinate count to create more prominent trails
    this.coordinates = [];
    this.coordinateCount = 3;
    // populate initial coordinate collection with the current coordinates
    while( this.coordinateCount-- ) {
        this.coordinates.push( [ this.x, this.y ] );
    }
    this.angle = Math.atan2( ty - sy, tx - sx );
    this.speed = 2;
    this.acceleration = 1.05;
    this.brightness = random( 50, 70 );
    // circle target indicator radius
    this.targetRadius = 1;
}

// update firework
Firework.prototype.update = function( index ) {
    // remove last item in coordinates array
    this.coordinates.pop();
    // add current coordinates to the start of the array
    this.coordinates.unshift( [ this.x, this.y ] );
    
    // cycle the circle target indicator radius
    if( this.targetRadius < 8 ) {
        this.targetRadius += 0.3;
    } else {
        this.targetRadius = 1;
    }
    
    // speed up the firework
    this.speed *= this.acceleration;
    
    // get the current velocities based on angle and speed
    var vx = Math.cos( this.angle ) * this.speed,
            vy = Math.sin( this.angle ) * this.speed;
    // how far will the firework have traveled with velocities applied?
    this.distanceTraveled = calculateDistance( this.sx, this.sy, this.x + vx, this.y + vy );
    
    // if the distance traveled, including velocities, is greater than the initial distance to the target, then the target has been reached
    if( this.distanceTraveled >= this.distanceToTarget ) {
        createParticles( this.tx, this.ty );
        // remove the firework, use the index passed into the update function to determine which to remove
        fireworks.splice( index, 1 );
    } else {
        // target not reached, keep traveling
        this.x += vx;
        this.y += vy;
    }
}

// draw firework
Firework.prototype.draw = function() {
    ctx.beginPath();
    // move to the last tracked coordinate in the set, then draw a line to the current x and y
    ctx.moveTo( this.coordinates[ this.coordinates.length - 1][ 0 ], this.coordinates[ this.coordinates.length - 1][ 1 ] );
    ctx.lineTo( this.x, this.y );
    ctx.strokeStyle = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)';
    ctx.stroke();
    
    ctx.beginPath();
    // draw the target for this firework with a pulsing circle
    ctx.arc( this.tx, this.ty, this.targetRadius, 0, Math.PI * 2 );
    ctx.stroke();
}

// create particle
function Particle( x, y ) {
    this.x = x;
    this.y = y;
    // track the past coordinates of each particle to create a trail effect, increase the coordinate count to create more prominent trails
    this.coordinates = [];
    this.coordinateCount = 5;
    while( this.coordinateCount-- ) {
        this.coordinates.push( [ this.x, this.y ] );
    }
    // set a random angle in all possible directions, in radians
    this.angle = random( 0, Math.PI * 2 );
    this.speed = random( 1, 10 );
    // friction will slow the particle down
    this.friction = 0.95;
    // gravity will be applied and pull the particle down
    this.gravity = 1;
    // set the hue to a random number +-20 of the overall hue variable
    this.hue = random( hue - 20, hue + 20 );
    this.brightness = random( 50, 80 );
    this.alpha = 1;
    // set how fast the particle fades out
    this.decay = random( 0.015, 0.03 );
}

// update particle
Particle.prototype.update = function( index ) {
    // remove last item in coordinates array
    this.coordinates.pop();
    // add current coordinates to the start of the array
    this.coordinates.unshift( [ this.x, this.y ] );
    // slow down the particle
    this.speed *= this.friction;
    // apply velocity
    this.x += Math.cos( this.angle ) * this.speed;
    this.y += Math.sin( this.angle ) * this.speed + this.gravity;
    // fade out the particle
    this.alpha -= this.decay;
    
    // remove the particle once the alpha is low enough, based on the passed in index
    if( this.alpha <= this.decay ) {
        particles.splice( index, 1 );
    }
}

// draw particle
Particle.prototype.draw = function() {
    ctx. beginPath();
    // move to the last tracked coordinates in the set, then draw a line to the current x and y
    ctx.moveTo( this.coordinates[ this.coordinates.length - 1 ][ 0 ], this.coordinates[ this.coordinates.length - 1 ][ 1 ] );
    ctx.lineTo( this.x, this.y );
    ctx.strokeStyle = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')';
    ctx.stroke();
}

// create particle group/explosion
function createParticles( x, y ) {
    // increase the particle count for a bigger explosion, beware of the canvas performance hit with the increased particles though
    var particleCount = 30;
    while( particleCount-- ) {
        particles.push( new Particle( x, y ) );
    }
}

// main demo loop
function loop() {
    // this function will run endlessly with requestAnimationFrame
    requestAnimFrame( loop );
    
    // increase the hue to get different colored fireworks over time
    hue += 0.5;
    
    // normally, clearRect() would be used to clear the canvas
    // we want to create a trailing effect though
    // setting the composite operation to destination-out will allow us to clear the canvas at a specific opacity, rather than wiping it entirely
    ctx.globalCompositeOperation = 'destination-out';
    // decrease the alpha property to create more prominent trails
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.fillRect( 0, 0, cw, ch );
    // change the composite operation back to our main mode
    // lighter creates bright highlight points as the fireworks and particles overlap each other
    ctx.globalCompositeOperation = 'lighter';
    
    // loop over each firework, draw it, update it
    var i = fireworks.length;
    while( i-- ) {
        fireworks[ i ].draw();
        fireworks[ i ].update( i );
    }
    
    // loop over each particle, draw it, update it
    var i = particles.length;
    while( i-- ) {
        particles[ i ].draw();
        particles[ i ].update( i );
    }
    
    // launch fireworks automatically to random coordinates, when the mouse isn't down
    if( timerTick >= timerTotal ) {
        if( !mousedown ) {
            // start the firework at the bottom middle of the screen, then set the random target coordinates, the random y coordinates will be set within the range of the top half of the screen
            fireworks.push( new Firework( cw / 2, ch, random( 0, cw ), random( 0, ch / 2 ) ) );
            timerTick = 0;
        }
    } else {
        timerTick++;
    }
    
    // limit the rate at which fireworks get launched when mouse is down
    if( limiterTick >= limiterTotal ) {
        if( mousedown ) {
            // start the firework at the bottom middle of the screen, then set the current mouse coordinates as the target
            fireworks.push( new Firework( cw / 2, ch, mx, my ) );
            limiterTick = 0;
        }
    } else {
        limiterTick++;
    }
}

// mouse event bindings
// update the mouse coordinates on mousemove
canvas.addEventListener( 'mousemove', function( e ) {
    mx = e.pageX - canvas.offsetLeft;
    my = e.pageY - canvas.offsetTop;
});

// toggle mousedown state and prevent canvas from being selected
canvas.addEventListener( 'mousedown', function( e ) {
    e.preventDefault();
    mousedown = true;
});

canvas.addEventListener( 'mouseup', function( e ) {
    e.preventDefault();
    mousedown = false;
});

// once the window loads, we are ready for some fireworks!
window.onload = loop;
</script>

6、烟花喷泉

 

 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Canvas烟花喷泉动画特效</title>

<script src="js/jquery-1.8.3.min.js"></script>

<style>
* {
    padding:0;
    margin:0;
}
html,body {
    position:relative;
    width:100%;
    height:100%;
}
body {
    background:#eee;
}
canvas {
    background:black;
    display:block;
    position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%,-50%);
}
</style>

</head>
<body>

<canvas id="c"></canvas>

<script>
    ;(function(main) {
        main();
    })(function() {

        'use strict';

        var c = document.getElementById('c');
        var ctx = c.getContext('2d');
        var W = c.width = window.innerWidth;
        var H = c.height = window.innerHeight;
        var CX = W / 2;
        var CY = H / 2;

        

        var Particle = function(x, y, vx, vy) {
            this.x = x;
            this.y = y;
            this.ox = x;
            this.oy = y;
            this.vx = vx;
            this.vy = vy;
            this.alpha = Math.random();
            this.color = 25;
            this.lineWidth = Math.random() * 4;
        };

        Particle.prototype = {
            constructor: Particle,
            update: function() {

                this.vx += Math.random() * 0.5 - 0.25;
                this.vy += 0.8;
                this.vy *= 0.98;
                this.alpha *= 0.95;

                this.ox = this.x;
                this.oy = this.y;
                this.x += this.vx;
                this.y += this.vy;

                if(this.y < 0 || this.y > H || this.alpha < 0.1) {
                    this.vx = Math.random() * 2 - 1;
                    this.vy = Math.random() * -50;
                    this.ox = this.x = CX;
                    this.oy = this.y = H;
                    this.alpha = Math.random();
                }

            },
            render: function(ctx) {
                ctx.save();
                ctx.globalAlpha = 0.98;
                ctx.lineWidth = this.lineWidth;
                ctx.strokeStyle = 'hsla(' + (this.color) + ', 100%, 50%, ' + this.alpha + ')';
                ctx.beginPath();
                ctx.moveTo(this.ox, this.oy);
                ctx.lineTo(this.x, this.y);
                ctx.stroke();
                ctx.restore();
            }
        };



        var particleCount = 500;
        var particle = null;
        var particles = [];
        var interval = 0;

        for(var i = 0; i < 250; i++) {
            particle = new Particle(
                CX,
                H,
                Math.random() * 2 - 1,
                Math.random() * -50
            );            
            particles.push(particle);            
        }


        requestAnimationFrame(function loop() {
            requestAnimationFrame(loop);

            ctx.globalCompositeOperation = 'source-over';
            ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
            ctx.fillRect(0, 0, W, H);

            ctx.globalCompositeOperation = 'lighter';

            if(particles.length < particleCount) {
                particle = new Particle(
                    CX,
                    H,
                    Math.random() * 2 - 1,
                    Math.random() * -50
                );            
                particles.push(particle);
            } 

            for(var i = 0, len = particles.length; i < len; i++) {
                particle = particles[i];
                particle.update();
                particle.render(ctx);                
            }


        });
        
    });
</script>

</body>
</html>

 

标签:function,特效,canvas,const,random,烟花,var,Math
From: https://www.cnblogs.com/art-poet/p/16911292.html

相关文章

  • osgearth仿真平台之特效(4)
    osgearth特效主要是开发了圆锥波、菱形波、干扰、通信、爆炸等特效,因为特效开发起来比较麻烦,有时候在osg上效果很好,放到osgearth上效果就不行了,特效如下:卫星轨道的添加: ......
  • 移动端-常见特效
    移动端-常见特效1.classList属性classList属性是HTML5新增的一个属性,返回元素的类名。但是ie10以上版本支持。该属性用于在元素中添加,移除及切换CSS类。有以下方法添加......
  • 心型特效
    <!DOCTYPEhtml><htmllang="en"><head'content-type':'application/x-www-form-urlencoded'><metacharset="UTF-8"><title>我爱你</title><stylet......
  • Python图像处理丨5种图像处理特效
    摘要:本篇文章主要讲解了图像常见的特效处理,从处理效果图、算法原理、代码实现三个步骤进行详细讲解,涉及图像素描特效、怀旧特效、光照特效、流年特效、图像滤镜等。本文分......
  • Python图像处理丨5种图像处理特效
    摘要:本篇文章主要讲解了图像常见的特效处理,从处理效果图、算法原理、代码实现三个步骤进行详细讲解,涉及图像素描特效、怀旧特效、光照特效、流年特效、图像滤镜等。本文分享......
  • PC端网页特效-元素滚动scroll系列
    PC端网页特效-元素滚动scroll系列1.scroll元素系列属性scroll翻译过来就是滚动的,我们使用scroll系列的相关属性可以动态的得到该元素的大小、滚动距离等。scroll系列......
  • PC端网页特效-元素可视区 client 系列
    PC端网页特效-元素可视区client系列client翻译过来就是客户端,我们使用client系列的相关属性来获取元素可视区的相关信息。通过client系列的相关属性可以动态的得到该元......
  • UGUI 3D粒子特效裁剪,层级,适配
    Unity里默认的粒子特效是3D渲染方式的,而UGUI又是特殊的渲染方式。如果想在UI里直接放入粒子特效,会导致:分层问题,粒子特效的层级排序由Z轴以及sortlayer决定,而UI的层级排......
  • 3D银河系例子动画js特效
    3D银河系例子动画js特效安装好nodejs就可以运行了。三个文件,全部源代码。链接:https://pan.baidu.com/s/1LjXFDZ9ocKL6ArZb9QWWtg?pwd=0011提取码:0011 ......
  • 基于Echarts实现可视化数据大屏echarts圆形波浪百分比图表特效
    前言......