在没风的地方找太阳  在你冷的地方做暖阳 人事纷纷  你总太天真  往后的余生  我只要你 往后余生  风雪是你  平淡是你  清贫也是你 荣华是你  心底温柔是你  目光所致  也是你 想带你去看晴空万里  想大声告诉你我为你着迷 往事匆匆  你总会被感动  往后的余生  我只要你 往后余生  冬雪是你  春花是你  夏雨也是你 秋黄是你  四季冷暖是你  目光所致  也是你 往后余生  风雪是你  平淡是你  清贫也是你 荣华是你  心底温柔是你  目光所致  也是你
jQuery火箭图标返回顶部代码 - 站长素材

烟花特效

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、

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=gbk" />
    <title>过年好</title>
    <script type="text/javascript">

      <style>
      html,body{
          margin:80px;
          width:100%;
          height:100%;
          overflow:hidden;
          background:#80;
      }

      #canvas{
          width:300%;
          height:300%;
      }
    </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>
    <audio src="audio/"></audio>
    <canvas id="canvas" width="1888" height="790"></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 = 0.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 = 0.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 = 0.1 - Math.random() * 0.2;
        seed.vy = -1.5; //*(1+Math.random()/2);
        seed.vz = 0.1 - Math.random() * 0.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 -= 0.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((0.5 + Math.sin(col) * 0.5) * 16);
        var g = parseInt((0.5 + Math.cos(col) * 0.5) * 16);
        var b = parseInt((0.5 - Math.sin(col) * 0.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>

 

 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>

 

7、

 

 

 

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>新年烟花</title>
  <style>
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0
    }

    ul,
    li {
      text-indent: 0;
      text-decoration: none;
      margin: 0;
      padding: 0
    }

    img {
      border: 0
    }

    body {
      background-color: #000;
      color: #999;
      font: 100%/18px helvetica, arial, sans-serif;
    }

    canvas {
      cursor: crosshair;
      display: block;
      left: 0;
      position: absolute;
      top: 0;
      z-index: 20
    }

    #moon {
      margin-top: 30px;
      margin-left: 900px;
    }

    #text {
      color: #ffdf00;
      font-size: 50px;
      position: absolute;
      top: 100px;
      left: 50%;
      transform: translateX(-50%);
      filter: url(#text-filter);
      text-shadow: 0 5px 15px #ff0000ed;
      letter-spacing: 10px;
    }

    .pull-rope {
      position: absolute;
      top: 0;
      left: 40px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .mode {
      width: 100px;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: url(https://img2.baidu.com/it/u=580689249,230811503&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=234);
      background-size: 100% 100%;
      font-weight: bold;
    }

    .rope {
      width: 10px;
      height: 300px;
      border-radius: 0 0 5px 5px;
      background: darkorange;
      z-index: 99;
    }
  </style>

</head>

<body>

  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  <script type="text/javascript">
    $(function () {
      //烟花
      var Fireworks = function () {
        var self = this;
        var rand = function (rMi, rMa) {
          return ~~((Math.random() * (rMa - rMi + 1)) + rMi);
        }
        var hitTest = function (x1, y1, w1, h1, x2, y2, w2, h2) {
          return !(x1 + w1 < x2 || x2 + w2 < x1 || y1 + h1 < y2 || y2 + h2 < y1);
        };
        /**window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。
      该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行
      封装一下,可以兼容所有浏览器*/
        window.requestAnimFrame = function () {
          return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window
            .mozRequestAnimationFrame || window.oRequestAnimationFrame || window
              .msRequestAnimationFrame || function (a) {
                window.setTimeout(a, 1E3 / 60)
              }
        }();
        //初始化,创建画布,和初始化需要的参数
        self.init = function () {
          self.mode = "auto"
          self.canvas = document.createElement('canvas');
          self.canvas.width = self.cw = $(window).innerWidth();
          self.canvas.height = self.ch = $(window).innerHeight();
          self.particles = [];
          self.partCount = 150;
          self.fireworks = [];
          self.mx = self.cw / 2;
          self.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 = true;
          self.showTarget = false;
          self.clearAlpha = 25;

          $(document.body).append(self.canvas);
          self.ctx = self.canvas.getContext('2d');
          self.ctx.lineCap = 'round';
          self.ctx.lineJoin = 'round';
          self.lineWidth = 1;
          self.bindEvents();
          self.canvasLoop();

          self.canvas.onselectstart = function () {
            return false;
          };
        };
        //创建烟花粒子
        self.createParticles = function (x, y, hue) {
          var countdown = self.partCount;
          while (countdown--) {
            var newParticle = {
              x: x,
              y: y,
              coordLast: [{
                x: x,
                y: y
              },
              {
                x: x,
                y: y
              },
              {
                x: x,
                y: y
              }
              ],
              angle: rand(0, 360),
              speed: rand(((self.partSpeed - self.partSpeedVariance) <= 0) ? 1 : self
                .partSpeed - self.partSpeedVariance, (self.partSpeed + self
                  .partSpeedVariance)),
              friction: 1 - self.partFriction / 100,
              gravity: self.partGravity / 2,
              hue: rand(hue - self.hueVariance, hue + self.hueVariance),
              brightness: rand(50, 80),
              alpha: rand(40, 100) / 100,
              decay: rand(10, 50) / 1000,
              wind: (rand(0, self.partWind) - (self.partWind / 2)) / 25,
              lineWidth: self.lineWidth
            };
            self.particles.push(newParticle);
          }
        };

        //更新烟花粒子
        self.updateParticles = function () {
          var i = self.particles.length;
          while (i--) {
            var p = self.particles[i];
            var radians = p.angle * Math.PI / 180;
            var vx = Math.cos(radians) * p.speed;
            var vy = Math.sin(radians) * 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 = function () {
          var i = self.particles.length;
          while (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 randAlpha = rand(50, 100) / 100;
                self.ctx.fillStyle = 'hsla(' + p.hue + ', 100%, ' + p.brightness + '%, ' +
                  randAlpha + ')';
                self.ctx.fill();
              }
            }
          };
        };

        //创建烟花
        self.createFireworks = function (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,
            speed: self.fworkSpeed,
            angle: Math.atan2(targetY - startY, targetX - startX),
            shockwaveAngle: Math.atan2(targetY - startY, targetX - startX) + (90 * (Math.PI /
              180)),
            acceleration: self.fworkAccel / 100,
            hue: self.currentHue,
            brightness: rand(50, 80),
            alpha: rand(50, 100) / 100,
            lineWidth: self.lineWidth
          };
          self.fireworks.push(newFirework);

        };

        //更新烟花参数
        self.updateFireworks = function () {
          var i = self.fireworks.length;

          while (i--) {
            var f = self.fireworks[i];
            self.ctx.lineWidth = f.lineWidth;

            vx = Math.cos(f.angle) * f.speed,
              vy = Math.sin(f.angle) * f.speed;
            f.speed *= 1 + f.acceleration;
            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) {
                f.x = f.targetX;
                f.hitX = true;
              } else {
                f.x += vx;
              }
            } else {
              if (f.x + vx >= f.targetX) {
                f.x = f.targetX;
                f.hitX = true;
              } else {
                f.x += vx;
              }
            }

            if (f.startY >= f.targetY) {
              if (f.y + vy <= f.targetY) {
                f.y = f.targetY;
                f.hitY = true;
              } else {
                f.y += vy;
              }
            } else {
              if (f.y + vy >= f.targetY) {
                f.y = f.targetY;
                f.hitY = true;
              } else {
                f.y += vy;
              }
            }

            if (f.hitX && f.hitY) {
              self.createParticles(f.targetX, f.targetY, f.hue);
              self.fireworks.splice(i, 1);

            }
          };
        };
        //绘制烟花
        self.drawFireworks = function () {
          var i = self.fireworks.length;
          self.ctx.globalCompositeOperation = 'lighter';
          while (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.brightness + '%, ' + 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.autoPlayTimer = null
        self.autoPlay = function () {
          let maxW = window.screen.width
          let maxH = window.screen.height
          let x = Math.floor(Math.random() * (maxW - 300)) + 150;
          let y = Math.floor(Math.random() * (maxH - 250));
          fworks.mx = x - fworks.canvas.offsetLeft;
          fworks.my = y - fworks.canvas.offsetTop;
          fworks.currentHue = rand(fworks.hueMin, fworks.hueMax);
          fworks.createFireworks(fworks.cw / 2, fworks.ch, fworks.mx, fworks.my);
        }
        //绑定事件
        self.bindEvents = function () {

          $('.rope').on('click', function (e) {
            e.stopPropagation();
            $('.rope').animate({ height: '400px' }, 500, function () {
              $('.rope').animate({ height: '300px' }, 500)
            })
            //切换手动
            self.mode = self.mode === 'auto' ? 'Manual' : 'auto'
            $('.mode').text(self.mode === 'auto' ? '自 动' : '手 动')
            clearInterval(self.autoPlayTimer)
            self.autoPlayTimer = null
          });

          $(window).on('click', function () {
            if (self.mode == 'Manual') return
            if (self.autoPlayTimer) {
              clearInterval(self.autoPlayTimer)
              self.autoPlayTimer = null
            } else {
              self.autoPlayTimer = setInterval(function () {
                self.autoPlay()
              }, 100)
            }
          });

          $(window).on('resize', function () {
            clearTimeout(self.timeout);
            self.timeout = setTimeout(function () {
              self.canvas.width = self.cw = $(window).innerWidth();
              self.canvas.height = self.ch = $(window).innerHeight();
              self.ctx.lineCap = 'round';
              self.ctx.lineJoin = 'round';
            }, 100);
          });

          $(self.canvas).on('mousedown', function (e) {
            if (self.mode == 'auto') return
            self.mx = e.pageX - self.canvas.offsetLeft;
            self.my = e.pageY - self.canvas.offsetTop;
            console.log(e.pageY)
            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) {
              if (self.mode == 'auto') return
              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) {
            if (self.mode == 'auto') return
            $(self.canvas).off('mousemove.fireworks');
          });

        }

        self.clear = function () {
          self.particles = [];
          self.fireworks = [];
          self.ctx.clearRect(0, 0, self.cw, self.ch);
        };


        self.canvasLoop = function () {
          //requestAnimationFrame是浏览器用于定时循环操作的一个接口,类似于setTimeout,主要用途是按帧对网页进行重绘。        
          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();

    });
  </script>
  <img id="moon" src="https://img1.baidu.com/it/u=726891218,2328235929&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500"
    width="400px" ;height="400px" ; />

  <p id="text">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
  </p>

  <div class="pull-rope">
    <div class="mode">自 动</div>
    <div class="rope"></div>
  </div>

  <svg width="0" height="0">
    <filter id="text-filter">

      <!--定义feTurbulence滤镜-->
      <feTurbulence baseFrequency="0.02" seed="0">

        <!--这是svg动画的定义方式,通过动画不断改变seed的值,形成抖动效果-->
        <animate attributeName="seed" dur="1s" keyTimes="0;0.5;1" values="1;2;3" repeatCount="indefinite">
        </animate>
      </feTurbulence>
      <feDisplacementMap in="SourceGraphic" scale="10" />
    </filter>
  </svg>
</body>

</html>

 

posted @ 2022-11-21 14:16  艺术诗人  阅读(71)  评论(0编辑  收藏  举报