首页 前端知识 2023年跨年烟花---源码

2023年跨年烟花---源码

2024-01-28 12:01:22 前端知识 前端哥 344 305 我要收藏

没有编程也可以做烟花系列

2023年款跨年烟花

 

1.首先,打开文件资源管理系统,你需要在自己的电脑上创建一个文本文件

2.打开文本文件,并将下面的代码复制到该文本文件里面

​​<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Happy 2023新年快乐!</title>
  </head>
  <body>
    <script src="js/gameCanvas-4.0.js"></script>
    <script src="js/script.js"></script>
    <!--live2d-->
    <script src="https://blog-static.cnblogs.com/files/zouwangblog/autoload.js"></script>
    <!--live2dend-->

    <!--放大图片-->
    <link
      rel="stylesheet"
      type="text/css"
      href="https://blog-static.cnblogs.com/files/zouwangblog/zoom.css"
    />
    <script src="https://cdn.bootcss.com/jquery/1.8.3/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.2.0/js/transition.js"></script>
    <script src="https://blog-static.cnblogs.com/files/zouwangblog/zoom.js"></script>
    <script type="text/javascript">
      $("#cnblogs_post_body img").attr("data-action", "zoom");
    </script>
    <!--放大图片end-->

    <!--鼠标特效-->
    <script src="https://blog-static.cnblogs.com/files/zouwangblog/mouse-click.js"></script>
    <canvas
      width="1777"
      height="841"
      style="
        position: fixed;
        left: 0px;
        top: 0px;
        z-index: 2147483647;
        pointer-events: none;
      "
    ></canvas>
    <!--鼠标特效 end-->
    <!-- 友链 -->
    <input id="linkListFlg" type="hidden" />

    <!-- require APlayer -->
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css"
    />
    <script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script>
    <!-- require MetingJS -->
    <script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>
    <meting-js
      id="2829883282"
      lrc-type="0"
      server="netease"
      order="random"
      type="playlist"
      fixed="true"
      autoplay="false"
      list-olded="true"
    >
    </meting-js>

    <!-- // 随机线条 -->
    <script>
      !(function () {
        function n(n, e, t) {
          return n.getAttribute(e) || t;
        }
        function e(n) {
          return document.getElementsByTagName(n);
        }
        function t() {
          var t = e("script"),
            o = t.length,
            i = t[o - 1];
          return {
            l: o,
            z: n(i, "zIndex", -1),
            o: n(i, "opacity", 0.6),
            c: n(i, "color", "148,0,211"),
            n: n(i, "count", 99),
          };
        }
        function o() {
          (a = m.width =
            window.innerWidth ||
            document.documentElement.clientWidth ||
            document.body.clientWidth),
            (c = m.height =
              window.innerHeight ||
              document.documentElement.clientHeight ||
              document.body.clientHeight);
        }
        function i() {
          r.clearRect(0, 0, a, c);
          var n, e, t, o, m, l;
          s.forEach(function (i, x) {
            for (
              i.x += i.xa,
                i.y += i.ya,
                i.xa *= i.x > a || i.x < 0 ? -1 : 1,
                i.ya *= i.y > c || i.y < 0 ? -1 : 1,
                r.fillRect(i.x - 0.5, i.y - 0.5, 1, 1),
                e = x + 1;
              e < u.length;
              e++
            )
              (n = u[e]),
                null !== n.x &&
                  null !== n.y &&
                  ((o = i.x - n.x),
                  (m = i.y - n.y),
                  (l = o * o + m * m),
                  l < n.max &&
                    (n === y &&
                      l >= n.max / 2 &&
                      ((i.x -= 0.03 * o), (i.y -= 0.03 * m)),
                    (t = (n.max - l) / n.max),
                    r.beginPath(),
                    (r.lineWidth = t / 2),
                    (r.strokeStyle = "rgba(" + d.c + "," + (t + 0.2) + ")"),
                    r.moveTo(i.x, i.y),
                    r.lineTo(n.x, n.y),
                    r.stroke()));
          }),
            x(i);
        }
        var a,
          c,
          u,
          m = document.createElement("canvas"),
          d = t(),
          l = "c_n" + d.l,
          r = m.getContext("2d"),
          x =
            window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function (n) {
              window.setTimeout(n, 1e3 / 45);
            },
          w = Math.random,
          y = { x: null, y: null, max: 2e4 };
        (m.id = l),
          (m.style.cssText =
            "position:fixed;top:0;left:0;z-index:" + d.z + ";opacity:" + d.o),
          e("body")[0].appendChild(m),
          o(),
          (window.onresize = o),
          (window.onmousemove = function (n) {
            (n = n || window.event), (y.x = n.clientX), (y.y = n.clientY);
          }),
          (window.onmouseout = function () {
            (y.x = null), (y.y = null);
          });
        for (var s = [], f = 0; d.n > f; f++) {
          var h = w() * a,
            g = w() * c,
            v = 2 * w() - 1,
            p = 2 * w() - 1;
          s.push({ x: h, y: g, xa: v, ya: p, max: 6e3 });
        }
        (u = s.concat([y])),
          setTimeout(function () {
            i();
          }, 100);
      })();
    </script>

    <!-- 雪花特效 -->
    <script type="text/javascript">
      (function ($) {
        $.fn.snow = function (options) {
          var $flake = $('<div id="snowbox" />')
              .css({ position: "absolute", "z-index": "9999", top: "-50px" })
              .html("❄"),
            documentHeight = $(document).height(),
            documentWidth = $(document).width(),
            defaults = {
              minSize: 10,
              maxSize: 20,
              newOn: 1000,
              flakeColor:
                "#00CED1" /* 此处可以定义雪花颜色,若要白色可以改为#FFFFFF */,
            },
            options = $.extend({}, defaults, options);
          var interval = setInterval(function () {
            var startPositionLeft = Math.random() * documentWidth - 100,
              startOpacity = 0.5 + Math.random(),
              sizeFlake = options.minSize + Math.random() * options.maxSize,
              endPositionTop = documentHeight - 200,
              endPositionLeft = startPositionLeft - 500 + Math.random() * 500,
              durationFall = documentHeight * 10 + Math.random() * 5000;
            $flake
              .clone()
              .appendTo("body")
              .css({
                left: startPositionLeft,
                opacity: startOpacity,
                "font-size": sizeFlake,
                color: options.flakeColor,
              })
              .animate(
                {
                  top: endPositionTop,
                  left: endPositionLeft,
                  opacity: 0.2,
                },
                durationFall,
                "linear",
                function () {
                  $(this).remove();
                }
              );
          }, options.newOn);
        };
      })(jQuery);
      $(function () {
        $.fn.snow({
          minSize: 5 /* 定义雪花最小尺寸 */,
          maxSize: 80 /* 定义雪花最大尺寸 */,
          newOn: 200 /* 定义密集程度,数字越小越密集 */,
        });
      });
    </script>
  </body>
</html>

 

3.保存,退出,然后将该文本文件改名为index.html文件类型

 4.创建一个文件夹,并且重命名为js

 5.打开js文件夹,创建两个文本文件,将下面的代码分别复制粘贴到两个文本文档里面,保存退出后,分别改名为gameCanvas-4.0.js,script.js。

gameCanvas-4.0.js

function GameCanvas(settings) {
  let top = this;

  this.functions = [];
  this.keys = [];
  this.images = [];
  this.spheres = [];
  this.font = "Arial";
  this.imageData = undefined;
  this.imageDataData = undefined;
  this.lastLoop = performance.now();
  this.calculateFPS = true;
  this.fps = -1;
  this.deltaTime = 1;
  let mouseLookupTable = [
    "left",
    "middle",
    "right"
  ];
  this.contextMenuDisabled = false;
  this.disableScrollOnMobile = false;
  this.eventFunctions = {
    "mousedown": typeof OnMouseDown !== "undefined",
    "mouseup": typeof OnMouseUp !== "undefined",
    "mousemove": typeof OnMouseMove !== "undefined",
    "contextmenu": typeof OnContextMenu !== "undefined",
    "touchstart": typeof OnTouchStart !== "undefined",
    "touchend": typeof OnTouchEnd !== "undefined",
    "touchmove": typeof OnTouchMove !== "undefined",
  };
  this.audioContext = new (window.AudioContext || window.webkitAudioContext)();

  this.createCanvas = function () {
    let canvas = document.createElement("canvas");
    document.body.appendChild(canvas);
    return canvas;
  }
  this.setSize = function (width, height) {
    if (top.canvas) {
      top.canvas.width = top.width = width;
      top.canvas.height = top.height = height;
      window.width = this.width;
      window.height = this.height;
    }
    else {
      console.error("There is no canvas!");
    }
  }
  this.fillPageWithCanvas = function () {
    top.canvas.style.position = "fixed";
    top.canvas.style.top = "0px";
    top.canvas.style.left = "0px";
    top.setSize(window.innerWidth, window.innerHeight);
    top.disableScrollOnMobile = true;
    top.contextMenuDisabled = true;
    this.updateSizeOnResize = true;
  }
  this.requestFullscreen = function () {
    if (top.canvas.requestFullscreen)
      top.canvas.requestFullscreen();
    else if (top.canvas.mozRequestFullScreen)
      top.canvas.mozRequestFullScreen();
    else if (top.canvas.webkitRequestFullscreen)
      top.canvas.webkitRequestFullscreen();
    else if (top.canvas.msRequestFullscreen)
      top.canvas.msRequestFullscreen();
  }
  this.exitFullscreen = function () {
    if (document.exitFullscreen)
      document.exitFullscreen();
    else if (document.mozCancelFullScreen)
      document.mozCancelFullScreen();
    else if (document.webkitExitFullscreen)
      document.webkitExitFullscreen();
    else if (document.msExitFullscreen)
      document.msExitFullscreen();
  }
  this.lockPointer = function () {
    top.canvas.requestPointerLock = top.canvas.requestPointerLock || top.canvas.mozRequestPointerLock;
    top.canvas.requestPointerLock();
  }
  this.unlockPointer = function () {
    document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock;
    document.exitPointerLock();
  }
  this.disableContextMenu = function () {
    top.contextMenuDisabled = true;
  }
  this.enableContextMenu = function () {
    top.contextMenuDisabled = false;
  }

  this.key = function (key) {
    return top.keys[key];
  }

  this.update = function () {
    if (top.calculateFPS) {
      var thisLoop = performance.now();
      top.fps = 1000 / (thisLoop - top.lastLoop);
      top.deltaTime = 60 / top.fps;
      top.lastLoop = thisLoop;

      if (top.globalFunctions) {
        window.fps = top.fps;
        window.deltaTime = top.deltaTime;
      }
    }

    top.mouse.movementX = 0;
    top.mouse.movementY = 0;
    top.mouse.lastX = top.mouse.x;
    top.mouse.lastY = top.mouse.y;
  }

  /******************
  
       Rendering
     
   ******************/

  this.clearScreen = function () {
    top.ctx.clearRect(0, 0, top.width, top.height);
  }

  this.background = function (color) {
    top.ctx.fillStyle = color;
    top.ctx.fillRect(0, 0, top.width, top.height);
  }

  this.circle = function (x, y, radius, color, strokeColor, lineWidth) {
    top.ctx.beginPath();
    top.ctx.arc(x, y, radius, 0, Math.PI * 2);
    top.ctx.fillStyle = color;
    if (strokeColor) top.ctx.strokeStyle = strokeColor;
    if (lineWidth) top.ctx.lineWidth = lineWidth;
    top.ctx.fill();
    if (strokeColor) top.ctx.stroke();
  }

  this.ring = function (x, y, radius, color, lineWidth) {
    top.ctx.beginPath();
    top.ctx.arc(x, y, radius, 0, Math.PI * 2);
    top.ctx.strokeStyle = color;
    if (lineWidth) top.ctx.lineWidth = lineWidth;
    top.ctx.stroke();
  }

  this.ellipse = function (x, y, radiusX, radiusY, color, rotation = 0, strokeColor, lineWidth) {
    top.ctx.beginPath();
    top.ctx.ellipse(x, y, radiusX, radiusY, rotation, 0, Math.PI * 2);
    top.ctx.fillStyle = color;
    if (strokeColor) top.ctx.strokeStyle = strokeColor;
    if (lineWidth) top.ctx.lineWidth = lineWidth;
    top.ctx.fill();
    if (strokeColor) top.ctx.stroke();
  }

  this.rectangle = function (x, y, width, height, color, strokeColor, lineWidth) {
    top.ctx.fillStyle = color;
    if (lineWidth) top.ctx.lineWidth = lineWidth;
    if (strokeColor) {
      top.ctx.beginPath();
      top.ctx.strokeStyle = strokeColor;
      top.ctx.rect(x, y, width, height);
      top.ctx.fill();
      top.ctx.stroke();
    }
    else
      top.ctx.fillRect(x, y, width, height);
  }

  this.triangle = function (x1, y1, x2, y2, x3, y3, color, strokeColor, lineWidth) {
    top.ctx.beginPath();
    top.ctx.moveTo(x1, y1);
    top.ctx.lineTo(x2, y2);
    top.ctx.lineTo(x3, y3);
    top.ctx.closePath();
    top.ctx.fillStyle = color;
    if (lineWidth) top.ctx.lineWidth = lineWidth;
    top.ctx.fill();
    if (strokeColor) {
      top.ctx.strokeStyle = strokeColor;
      top.ctx.stroke();
    }
  }

  this.setLineCap = function (lineCap) {
    top.ctx.lineCap = lineCap;
  }

  this.resetLineCap = function () {
    top.ctx.lineCap = "butt";
  }

  this.line = function (x1, y1, x2, y2, strokeWeight, color) {
    top.ctx.beginPath();
    top.ctx.moveTo(x1, y1);
    top.ctx.lineTo(x2, y2);
    if (color) top.ctx.strokeStyle = color;
    if (strokeWeight) top.ctx.lineWidth = strokeWeight;
    top.ctx.stroke();
  }

  this.picture = function (url, x, y, width, height) {
    var imageElement = top.images[url];
    if (!imageElement) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        top.ctx.drawImage(img, x, y, width, height);
      }
      top.images[url] = img;
    }
    else if (imageElement.complete) {
      top.ctx.drawImage(imageElement, x, y, width, height);
    }
  }

  this.setFont = function (font) {
    top.font = font;
  }

  this.setTextAlign = function (align) {
    top.ctx.textAlign = align;
  }

  this.setTextXAlign = function (align) {
    top.ctx.textAlign = align;
  }

  this.setTextYAlign = function (align) {
    top.ctx.textBaseline = align;
  }

  this.resetTextXAlign = function () {
    top.ctx.textAlign = "left";
  }

  this.resetTextYAlign = function () {
    top.ctx.textBaseline = "alphabetic";
  }

  this.text = function (textString, x, y, fontSize, color, strokeColor, lineWidth) {
    top.ctx.beginPath();
    top.ctx.font = fontSize + "px " + top.font;
    top.ctx.fillStyle = color;
    if (lineWidth) top.ctx.lineWidth = lineWidth;
    top.ctx.fillText(textString, x, y);
    if (strokeColor) {
      top.ctx.strokeStyle = strokeColor;
      top.ctx.strokeText(textString, x, y);
    }
  }

  this.getPixelData = function () {
    top.imageData = top.ctx.getImageData(0, 0, top.width, top.height);
    top.imageDataData = top.imageData.data;
  }

  this.updatePixel = function (x, y, r, g, b, a = 255) {
    let i = (x + y * top.width) * 4;
    top.imageDataData[i] = r;
    top.imageDataData[i + 1] = g;
    top.imageDataData[i + 2] = b;
    top.imageDataData[i + 3] = a;
  }

  this.updatePixelIndex = function (index, r, g, b, a = 255) {
    var i = index * 4;
    top.imageDataData[i] = r;
    top.imageDataData[i + 1] = g;
    top.imageDataData[i + 2] = b;
    top.imageDataData[i + 3] = a;
  }

  this.getPixel = function (x, y) {
    let i = (x + y * top.width) * 4;
    return [
      top.imageDataData[i],
      top.imageDataData[i + 1],
      top.imageDataData[i + 2],
      top.imageDataData[i + 3]
    ];
  }

  this.getPixelIndex = function (index) {
    let i = index * 4;
    return [
      top.imageDataData[i],
      top.imageDataData[i + 1],
      top.imageDataData[i + 2],
      top.imageDataData[i + 3]
    ];
  }

  this.renderPixelData = function () {
    /*createImageBitmap(top.imageData).then(function(imgBitmap) {
      top.ctx.drawImage(imgBitmap, 0, 0);
    });*/

    top.ctx.putImageData(top.imageData, 0, 0);
  }

  this.save = function () {
    top.ctx.save();
  }

  this.restore = function () {
    top.ctx.restore();
  }

  this.rotate = function (angle) {
    top.ctx.rotate(angle);
  }

  this.translate = function (x, y) {
    top.ctx.translate(x, y);
  }

  this.beginPath = function () {
    top.ctx.beginPath();
  }

  this.closePath = function () {
    top.ctx.closePath();
  }

  this.moveTo = function (x, y) {
    top.ctx.moveTo(x, y);
  }

  this.lineTo = function (x, y) {
    top.ctx.lineTo(x, y);
  }

  this.fill = function () {
    top.ctx.fill();
  }

  this.stroke = function () {
    top.ctx.stroke();
  }

  this.fillStyle = function (color) {
    top.ctx.fillStyle = color;
  }

  this.strokeStyle = function (color) {
    top.ctx.strokeStyle = color;
  }

  this.setLineWidth = function (lineWidth) {
    top.ctx.lineWidth = lineWidth;
  }

  /******************
  
       3D
     
   ******************/

  this.drawSphere = function (screenX, screenY, radius, color, lightDir = { x: 0, y: 0, z: 1 }) {
    var id = (screenX + screenY) * radius * (color[0] + 1) * (color[1] + 1) * (color[2] + 1) * (lightDir.x + 1) * (lightDir.y + 1) * (lightDir.z + 1);
    if (top.spheres[id]) {
      if (top.spheres[id].imageData)
        top.ctx.putImageData(top.spheres[id].imageData, screenX - radius, screenY - radius);
      else if (top.spheres[id].image)
        top.ctx.drawImage(top.spheres[id].image, screenX - radius, screenY - radius);
    }
    else {
      var imageData = top.ctx.createImageData(radius * 2, radius * 2);

      for (var y = 0; y < radius * 2; y++) {
        for (var x = 0; x < radius * 2; x++) {
          var line = {
            origin: { x: x, y: y, z: 0 },
            direction: { x: 0, y: 0, z: 1 }
          };
          var o = {
            position: { x: radius, y: radius, z: radius * 2 }
          }

          var oc = {
            x: line.origin.x - o.position.x,
            y: line.origin.y - o.position.y,
            z: line.origin.z - o.position.z
          };
          var loc = top.dot3D(line.direction, oc);
          var ocLength = top.getLength(oc.x, oc.y, oc.z);
          var underSqrt = loc * loc - (ocLength * ocLength - radius * radius);

          if (underSqrt >= 0) {
            var d = -loc - Math.sqrt(underSqrt);
            if (d > 0) { // Circle is not behind player and is closest to player
              var hitPoint = {
                x: line.origin.x + line.direction.x * d,
                y: line.origin.y + line.direction.y * d,
                z: line.origin.z + line.direction.z * d
              };
              var surfaceNormal = top.normalize3DVector({
                x: o.position.x - hitPoint.x,
                y: o.position.y - hitPoint.y,
                z: o.position.z - hitPoint.z
              });

              var diffuse = top.dot3D(lightDir, surfaceNormal);

              var index = (x + y * radius * 2) * 4;
              imageData.data[index] = color[0] * diffuse;
              imageData.data[index + 1] = color[1] * diffuse;
              imageData.data[index + 2] = color[2] * diffuse;
              imageData.data[index + 3] = 255;
            }
          }
        }
      }

      if (window.createImageBitmap) {
        top.spheres[id] = { imageData: undefined, image: undefined };
        createImageBitmap(imageData).then(function (imgBitmap) {
          top.ctx.drawImage(imgBitmap, screenX - radius, screenY - radius);
          top.spheres[id] = { imageData: undefined, image: imgBitmap };
        });
      }
      else {
        top.ctx.putImageData(imageData, screenX - radius, screenY - radius);
        top.spheres[id] = { imageData, image: undefined };
      }
    }
  }

  /******************
  
       Audio
     
   ******************/

  this.createSound = function (url, volume = 1, startTime = 0, looping = false) {
    var audio = new Audio(url);
    audio.loop = looping;
    audio.currentTime = startTime;
    audio.volume = volume;

    return {
      volume,
      startTime,
      audio
    };
  }

  this.playSound = function (sound) {
    sound.audio.currentTime = sound.startTime;
    sound.audio.volume = sound.volume;
    sound.audio.play();
  }

  this.stopSound = function (sound) {
    sound.audio.stop();
  }

  this.pauseSound = function (sound) {
    sound.audio.pause();
  }

  this.backgroundMusic = function (url) {
    var audio = new Audio(url);
    audio.loop = true;
    audio.play();
    return audio;
  }

  this.fadeOutSound = function (sound, time = 1) {
    var startVolume = sound.volume;
    var count = 0;
    var interv = setInterval(() => {
      sound.audio.volume = (startVolume / (time * 20)) * (time * 20 - count);
      count++;
      if (count > time * 20) {
        sound.audio.pause();
        clearInterval(interv);
      }
    }, 50);
  }

  this.playTone = function (freq = 440, time = 1, volume = 1, type = "sine") {
    var oscillator = top.audioContext.createOscillator();

    var gainNode = top.audioContext.createGain()
    gainNode.gain.value = volume;
    gainNode.connect(top.audioContext.destination);

    oscillator.type = type;
    oscillator.frequency.value = freq;
    oscillator.connect(gainNode);
    oscillator.start();

    setTimeout(() => {
      oscillator.stop();
    }, time * 1000);
  }

  /******************
  
       Math
     
   ******************/

  this.DegToRad = Math.PI / 180;
  this.RadToDeg = 180 / Math.PI;
  this.PI = Math.PI;
  this.TWO_PI = Math.PI * 2;
  this.TAU = this.TWO_PI;

  this.getDistanceSqr = function (x1, y1, x2, y2) {
    var a = x1 - x2;
    var b = y1 - y2;
    return a * a + b * b;
  }

  this.getDistanceSqr3D = function (x1, y1, x2, y2, z1, z2) {
    var a = x1 - x2;
    var b = y1 - y2;
    var c = z1 - z2;
    return a * a + b * b + c * c;
  }

  this.getDistance = function (x1, y1, x2, y2) {
    return Math.sqrt(top.getDistanceSqr(x1, y1, x2, y2));
  }

  this.getDistance3D = function (x1, y1, x2, y2, z1, z2) {
    return Math.sqrt(top.getDistanceSqr3D(x1, y1, x2, y2, z1, z2));
  }

  this.getAngle = function (x1, y1, x2, y2) {
    return Math.atan2(y2 - y1, x2 - x1);
  }

  this.normalize = function (x, y) {
    var len = Math.sqrt(x * x + y * y);
    return {
      x: x / len,
      y: y / len
    };
  }

  this.normalize3D = function (x, y, z) {
    var len = Math.sqrt(x * x + y * y + z * z);
    return {
      x: x / len,
      y: y / len,
      z: z / len
    };
  }

  this.normalize3DVector = function (x) {
    var len = Math.sqrt(x.x * x.x + x.y * x.y + x.z * x.z);
    return {
      x: x.x / len,
      y: x.y / len,
      z: x.z / len
    };
  }

  this.lengthVector = function (v) {
    return Math.sqrt(v.x * v.x + v.y * v.y);
  }

  this.length3DVector = function (v) {
    return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  }

  this.getLength = function () {
    var sum = 0;
    for (var i = 0; i < arguments.length; i++) {
      var arg = arguments[i];
      sum += arg * arg;
    }
    return Math.sqrt(sum);
  }

  this.dot = function (a, b) {
    return a.x * b.x + a.y * b.y;
  }

  this.dot3D = function (a, b) {
    return a.x * b.x + a.y * b.y + a.z * b.z;
  }

  this.crossProduct3D = function (v1, v2) {
    return {
      x: v1.y * v2.z - v1.z * v2.y,
      y: v1.z * v2.x - v1.x * v2.z,
      z: v1.x * v2.y - v1.y * v2.x
    }
  }

  //Intersection
  this.rectanglesIntersect = function (x1, y1, w1, h1, x2, y2, w2, h2) {
    return x1 + w1 > x2 && x1 < x2 + w2 && y1 + h1 > y2 && y1 < y2 + h2;
  }

  this.circlesIntersect = function (x1, y1, r1, x2, y2, r2) {
    return top.getDistance(x1, y1, x2, y2) < r1 + r2;
  }

  this.circleRectangleIntersect = function (x1, y1, r1, x2, y2, w2, h2) {
    var circleDistanceX = Math.abs(x1 - (x2 + w2 / 2));
    var circleDistanceY = Math.abs(y1 - (y2 + h2 / 2));

    if (circleDistanceX > (w2 / 2 + r1)) return false;
    if (circleDistanceY > (h2 / 2 + r1)) return false;

    if (circleDistanceX <= (w2 / 2)) return true;
    if (circleDistanceY <= (h2 / 2)) return true;

    var a = circleDistanceX - w2 / 2;
    var b = circleDistanceY - h2 / 2;
    var cornerDistance_sq = a * a + b * b;

    return cornerDistance_sq <= (r1 * r1);
  }

  //Random
  this.random = function (max) {
    return Math.random() * max;
  }

  this.randomInt = function (max) {
    return Math.random() * max >> 0;
  }

  this.randomArray = function (array) {
    return array[Math.random() * array.length >> 0];
  }

  this.randomColor = function (colorDepth) {
    if (colorDepth) {
      var colorStep = 256 / colorDepth;
      var r = Math.ceil((Math.random() * 256 >> 0) / colorStep) * colorStep;
      var g = Math.ceil((Math.random() * 256 >> 0) / colorStep) * colorStep;
      var b = Math.ceil((Math.random() * 256 >> 0) / colorStep) * colorStep;

      return "rgb(" + r + "," + g + "," + b + ")";
    }
    else {
      return "rgb(" + (Math.random() * 256 >> 0) + "," + (Math.random() * 256 >> 0) + "," + (Math.random() * 256 >> 0) + ")";
    }
  }

  this.create2DArray = function (w, h, value = () => 0) {
    var array = new Array(w);
    for (var i = 0; i < w; i++) {
      array[i] = new Array(h);
      for (var j = 0; j < h; j++) {
        array[i][j] = value(i, j);
      }
    }

    return array;
  }

  /******************
  
       Export
     
   ******************/

  this.canvasToURL = function () {
    return top.canvas.toDataURL();
  }

  this.canvasToImage = function () {
    var img = new Image();
    img.src = top.canvas.toDataURL();
    return img;
  }

  this.saveToFile = function (filename = "canvas.png") {
    var a = document.createElement("a");
    a.download = filename;
    a.href = top.canvas.toDataURL();
    a.click();
  }

  /******************
  
       Cookies
     
   ******************/

  this.setCookie = function (name, value, expireDays = 36500) {
    let d = new Date();
    d.setTime(d.getTime() + (expireDays * 24 * 60 * 60 * 1000));
    let expires = "expires=" + d.toUTCString();
    document.cookie = name + "=" + value + ";" + expires + ";path=/";
  }

  this.getCookie = function (name) {
    if (name.length == 0)
      return false;

    var cname = name + "=";
    var split = document.cookie.split(";");
    for (let i = 0; i < split.length; i++) {
      let s = split[i];
      var index = s.indexOf(cname);
      if (index > 0) {
        return s.substr(index + cname.length);
      }
    }
    return false;
  }

  this.deleteCookie = function (name) {
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/";
  }

  /******************
  
       Misc.
     
   ******************/

  //Battery level
  if (navigator.getBattery) {
    navigator.getBattery().then(function (battery) {
      battery.addEventListener('levelchange', function () {
        top.batteryLevel = battery.level * 100;
      });
      top.batteryLevel = battery.level * 100;
    });
  }

  this.getBatteryLevel = function () {
    return top.batteryLevel;
  }

  /******************
  
       Functions
     
   ******************/

  this.functions = [
    { func: this.createCanvas, name: "createCanvas" },
    { func: this.setSize, name: "setSize" },
    { func: this.fillPageWithCanvas, name: "fillPageWithCanvas" },
    { func: this.requestFullscreen, name: "requestFullscreen" },
    { func: this.exitFullscreen, name: "exitFullscreen" },
    { func: this.lockPointer, name: "lockPointer" },
    { func: this.unlockPointer, name: "unlockPointer" },
    { func: this.disableContextMenu, name: "disableContextMenu" },
    { func: this.enableContextMenu, name: "enableContextMenu" },
    { func: this.key, name: "key" },
    { func: this.update, name: "update" },

    { func: this.clearScreen, name: "clearScreen" },
    { func: this.background, name: "background" },
    { func: this.circle, name: "circle" },
    { func: this.ring, name: "ring" },
    { func: this.ellipse, name: "ellipse" },
    { func: this.rectangle, name: "rectangle" },
    { func: this.triangle, name: "triangle" },
    { func: this.picture, name: "picture" },
    { func: this.setLineCap, name: "setLineCap" },
    { func: this.resetLineCap, name: "resetLineCap" },
    { func: this.line, name: "line" },
    { func: this.setFont, name: "setFont" },
    { func: this.setTextAlign, name: "setTextAlign" },
    { func: this.setTextXAlign, name: "setTextXAlign" },
    { func: this.setTextYAlign, name: "setTextYAlign" },
    { func: this.resetTextXAlign, name: "resetTextXAlign" },
    { func: this.resetTextYAlign, name: "resetTextYAlign" },
    { func: this.text, name: "text" },
    { func: this.getPixelData, name: "getPixelData" },
    { func: this.updatePixel, name: "updatePixel" },
    { func: this.updatePixelIndex, name: "updatePixelIndex" },
    { func: this.getPixel, name: "getPixel" },
    { func: this.getPixelIndex, name: "getPixelIndex" },
    { func: this.renderPixelData, name: "renderPixelData" },
    { func: this.save, name: "save" },
    { func: this.restore, name: "restore" },
    { func: this.rotate, name: "rotate" },
    { func: this.translate, name: "translate" },
    { func: this.beginPath, name: "beginPath" },
    { func: this.closePath, name: "closePath" },
    { func: this.moveTo, name: "moveTo" },
    { func: this.lineTo, name: "lineTo" },
    { func: this.fill, name: "fill" },
    { func: this.stroke, name: "stroke" },
    { func: this.fillStyle, name: "fillStyle" },
    { func: this.strokeStyle, name: "strokeStyle" },
    { func: this.setLineWidth, name: "setLineWidth" },

    { func: this.drawSphere, name: "drawSphere" },

    { func: this.createSound, name: "createSound" },
    { func: this.playSound, name: "playSound" },
    { func: this.stopSound, name: "stopSound" },
    { func: this.pauseSound, name: "pauseSound" },
    { func: this.fadeOutSound, name: "fadeOutSound" },
    { func: this.playTone, name: "playTone" },

    { func: this.getDistanceSqr, name: "getDistanceSqr" },
    { func: this.getDistance, name: "getDistance" },
    { func: this.getDistanceSqr3D, name: "getDistanceSqr3D" },
    { func: this.getDistance3D, name: "getDistance3D" },
    { func: this.getAngle, name: "getAngle" },
    { func: this.normalize, name: "normalize" },
    { func: this.normalize3D, name: "normalize3D" },
    { func: this.normalize3D, name: "normalize3DVector" },
    { func: this.getLength, name: "getLength" },
    { func: this.dot, name: "dot" },
    { func: this.dot3D, name: "dot3D" },
    { func: this.crossProduct3D, name: "crossProduct3D" },
    { func: this.lengthVector, name: "lengthVector" },
    { func: this.length3DVector, name: "length3DVector" },

    { func: this.rectanglesIntersect, name: "rectanglesIntersect" },
    { func: this.circlesIntersect, name: "circlesIntersect" },
    { func: this.circleRectangleIntersect, name: "circleRectangleIntersect" },

    { func: this.random, name: "random" },
    { func: this.randomInt, name: "randomInt" },
    { func: this.randomArray, name: "randomArray" },
    { func: this.randomColor, name: "randomColor" },

    { func: this.create2DArray, name: "create2DArray" },

    { func: this.canvasToURL, name: "canvasToURL" },
    { func: this.canvasToImage, name: "canvasToImage" },
    { func: this.saveToFile, name: "saveToFile" },

    { func: this.setCookie, name: "setCookie" },
    { func: this.getCookie, name: "getCookie" },
    { func: this.deleteCookie, name: "deleteCookie" },

    { func: this.getBatteryLevel, name: "getBatteryLevel" }
  ];

  this.variables = [
    { variable: this.RadToDeg, name: "RadToDeg" },
    { variable: this.DegToRad, name: "DegToRad" },
    { variable: this.PI, name: "PI" },
    { variable: this.TWO_PI, name: "TWO_PI" },
    { variable: this.TAU, name: "TAU" }
  ];

  this.makeFunctionsGlobal = function () {
    this.globalFunctions = true;
    this.functions.forEach(item => {
      window[item.name] = item.func;
    });
    this.variables.forEach(item => {
      window[item.name] = item.variable;
    });

    window.fps = this.fps;
    window.deltaTime = this.deltaTime;
  }

  /******************
  
       Init
     
   ******************/

  this.settings = settings;
  if (typeof this.settings === 'undefined') {
    //Create a canvas and make it fullscreen
    this.canvas = this.createCanvas();
    this.fillPageWithCanvas();

    this.makeFunctionsGlobal();
  }
  else {
    if (typeof this.settings.canvas !== "undefined")
      this.canvas = this.settings.canvas;
    else {
      this.canvas = this.createCanvas();
      if (typeof this.settings.width === "undefined" &&
        typeof this.settings.height === "undefined")
        this.fillPageWithCanvas();

      if (typeof this.settings.globalFunctions === "undefined" || (typeof this.settings.globalFunctions !== "undefined" && this.settings.globalFunctions))
        this.makeFunctionsGlobal();
    }
    if (typeof this.settings.width !== "undefined") {
      this.width = this.settings.width;
      this.canvas.width = window.width = this.width;
    }
    if (typeof this.settings.height !== "undefined") {
      this.height = this.settings.height;
      this.canvas.height = window.height = this.height;
    }
    if (typeof this.settings.updateSizeOnResize !== "undefined") {
      this.updateSizeOnResize = this.settings.updateSizeOnResize;
    }
  }

  document.addEventListener("keydown", event => {
    this.keys[event.key] = this.keys[event.keyCode] = true;
  });
  document.addEventListener("keyup", event => {
    this.keys[event.key] = this.keys[event.keyCode] = false;
  });

  if (this.canvas) {
    this.ctx = this.canvas.getContext("2d");

    if (this.updateSizeOnResize) {
      window.addEventListener("resize", () => {
        this.setSize(window.innerWidth, window.innerHeight);
      });
    }

    this.mouse = { x: 0, y: 0, lastX: 0, lastY: 0, movementX: 0, movementY: 0, left: false, middle: false, right: false, down: false };
    this.touches = [];
    if (this.globalFunctions) {
      window.mouse = this.mouse;
      window.touches = this.touches;
    }

    this.canvas.addEventListener("mousemove", event => {
      let br = this.canvas.getBoundingClientRect();
      this.mouse.x = (event.clientX - br.left) / (br.width / this.width);
      this.mouse.y = (event.clientY - br.top) / (br.height / this.height);
      this.mouse.movementX = event.movementX;
      this.mouse.movementY = event.movementY;

      this.eventFunctions["mousemove"] && OnMouseMove(event);
    });

    this.canvas.addEventListener("mousedown", event => {
      let button = event.button;
      if (button < 3)
        this.mouse[mouseLookupTable[button]] = true;

      if (!this.audioContext)
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)();

      this.eventFunctions["mousedown"] && OnMouseDown(event);
    });

    this.canvas.addEventListener("mouseup", event => {
      let button = event.button;
      if (button < 3)
        this.mouse[mouseLookupTable[button]] = false;

      this.eventFunctions["mouseup"] && OnMouseUp(event);
    });

    this.canvas.addEventListener("contextmenu", event => {
      this.eventFunctions["contextmenu"] && OnContextMenu(event);

      if (this.contextMenuDisabled) {
        event.preventDefault();
        return false;
      }
      return true;
    });

    //Touch

    this.updateTouches = function () {
      let br = this.canvas.getBoundingClientRect();

      this.touches = [];
      for (let i = 0; i < event.touches.length; i++) {
        var e = event.touches[i];
        var x = (e.pageX - br.left) / (br.width / this.width);
        var y = (e.pageY - br.top) / (br.height / this.height);
        this.touches[i] = { x, y, id: e.identifier, force: e.force };
      }

      if (this.globalFunctions)
        window.touches = this.touches;
    }

    this.canvas.addEventListener("touchmove", event => {
      if (this.disableScrollOnMobile)
        event.preventDefault();

      this.updateTouches();
      this.mouse.x = this.touches[0].x;
      this.mouse.y = this.touches[0].y;

      this.eventFunctions["touchmove"] && OnTouchMove(event);
    });

    this.canvas.addEventListener("touchend", event => {
      if (this.disableScrollOnMobile)
        event.preventDefault();

      this.touches = [];
      if (this.globalFunctions)
        window.touches = this.touches;

      this.mouse.left = false;

      this.eventFunctions["touchend"] && OnTouchEnd(event);
    });

    this.canvas.addEventListener("touchstart", event => {
      if (this.disableScrollOnMobile)
        event.preventDefault();

      this.updateTouches();
      this.mouse.x = this.touches[0].x;
      this.mouse.y = this.touches[0].y;
      this.mouse.left = true;

      if (!this.audioContext)
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)();

      this.eventFunctions["touchstart"] && OnTouchStart(event);
    });
  }
}

script.js

 

var gc = new GameCanvas();

var points = textToPoints("2023新年快乐", 20, "Anton");


var titleParticles = [];
var fireworks = [];
var particles = [];

var gravity = 0.1;

setTimeout(function () {
  setInterval(function () {
    fireworks.push(new Firework(Math.random() * width, height, Math.random() - 0.5, -(Math.random() * 7 + 5)));
  }, 200);
}, 2000);

fireworks.push(new Firework(width / 2, height, 0, -9.5, 10, "gold", true));
setInterval(function () {
  fireworks.push(new Firework(width / 2, height, 0, -9.5, 10, "gold", true));
}, 5000);

for (var i = 0; i < 250; i++) {
  circle(
    Math.random() * width,
    Math.random() * height,
    1,
    "rgb(200, 200, 200)"
  );
}
var starImage = canvasToImage();

background("black");
loop();
function loop() {
  gc.ctx.globalCompositeOperation = "source-over";
  background("rgba(0, 0, 0, 0.1)");
  gc.ctx.drawImage(starImage, 0, 0);
  gc.ctx.globalCompositeOperation = "lighter";

  for (var i = 0; i < fireworks.length; i++) {
    var firework = fireworks[i];
    firework.update();
    firework.render();
  }

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

  for (var i = 0; i < titleParticles.length; i++) {
    var p = titleParticles[i];
    p.update();
    p.render();
  }

  requestAnimationFrame(loop);
}

function TitleParticle(x, y, vx, vy) {
  this.x = x;
  this.y = y;
  this.vx = vx;
  this.vy = vy;
  this.ay = 0.2;
  this.radius = 4;
  this.maxHealth = 200;
  this.health = 200;

  this.update = function () {
    this.x += this.vx;
    this.y += this.vy;
    this.vx *= 0.95;
    this.vy *= 0.95;
    this.vy += this.ay;
    this.ay *= 0.95;

    this.radius = (this.health / this.maxHealth) * 4;
    this.health--;
    if (this.health <= 0) {
      titleParticles.splice(titleParticles.indexOf(this), 1);
    }
  }

  this.render = function () {
    circle(this.x, this.y, this.radius, "rgba(255, 255, 255, " + (this.health / this.maxHealth) + ")");
  }
}

function Firework(x, y, vx, vy, radius = 5, color = "white", title = false) {
  this.x = x;
  this.y = y;
  this.vx = vx;
  this.vy = vy;
  this.radius = radius;
  this.title = title;
  this.color = color;

  this.update = function () {
    this.x += this.vx;
    this.y += this.vy;
    this.vy += gravity;

    if (this.vy >= 0) {
      fireworks.splice(fireworks.indexOf(this), 1);

      if (this.title) {
        var scale = 0.3;
        for (var i = 0; i < points.length; i++) {
          var p = points[i];
          var v = {
            x: (p.x - 60) * scale + (Math.random() - 0.5) * 0.1,
            y: (p.y - 20) * scale + (Math.random() - 0.5) * 0.1
          }
          var particle = new TitleParticle(this.x, this.y, v.x, v.y);
          titleParticles.push(particle);
        }
      }
      else {
        var color = [Math.random() * 256 >> 0, Math.random() * 256 >> 0, Math.random() * 256 >> 0];
        for (var i = 0; i < Math.PI * 2; i += 0.1) {
          var power = (Math.random() + 0.5) * 4;
          var vx = Math.cos(i) * power;
          var vy = Math.sin(i) * power;
          particles.push(new Particle(this.x, this.y, vx, vy, Math.random() + 3, color));
        }
      }
    }
  }

  this.render = function () {
    circle(this.x, this.y, this.radius, this.color);
  }
}

function Particle(x, y, vx, vy, radius, color) {
  this.x = x;
  this.y = y;
  this.vx = vx;
  this.vy = vy;
  this.life = 100;
  this.color = color;
  this.radius = radius;

  this.update = function () {
    this.x += this.vx;
    this.y += this.vy;
    this.vy += gravity;

    this.vx *= 0.95;
    this.vy *= 0.95;

    this.life--;
    if (this.life <= 0) {
      particles.splice(particles.indexOf(this), 1);
    }
  }

  this.render = function () {
    circle(this.x, this.y, 3 * (this.life / 100), "rgba(" + this.color[0] + ", " + this.color[1] + ", " + this.color[2] + ", " + (this.life / 100) + ")");
  }
}

function textToPoints(text, textSize, font) {
  var canvas = document.createElement("canvas");
  canvas.width = 1024;
  canvas.height = textSize * 1.3;
  var ctx = canvas.getContext("2d");

  ctx.textBaseline = "middle";
  ctx.font = textSize + "px " + font;
  ctx.fillText(text, 0, canvas.height / 2);

  var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  var data = imageData.data;

  var points = [];
  var index = (x, y) => (x + canvas.width * y) * 4;
  var threshold = 50;

  for (var i = 0; i < data.length; i += 4) {
    if (data[i + 3] > threshold) {
      var p = {
        x: (i / 4) % canvas.width,
        y: (i / 4) / canvas.width >> 0
      };

      if (data[index(p.x + 1, p.y) + 3] < threshold ||
        data[index(p.x - 1, p.y) + 3] < threshold ||
        data[index(p.x, p.y + 1) + 3] < threshold ||
        data[index(p.x, p.y - 1) + 3] < threshold) {
        points.push({
          x: (i / 4) % canvas.width,
          y: (i / 4) / canvas.width >> 0
        });
      }
    }
  }

  return points;
}

 6.最后点击index.html文件,就可以看见以下烟花了。

 注:左下角,可以点击播发音乐哦!

转载请注明出处或者链接地址:https://www.qianduange.cn//article/589.html
标签
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!