实战: 跨年烟花代码的实现(附源码)

news2024/11/15 17:32:32

目录

前言

一、pandas是什么?

二、代码结构

1.介绍主html代码

2. js文件介绍

GameCanvas.js

script.js

运行效果


前言

本文章将介绍跨年烟花代码的实现以及源代码


提示:以下是本篇文章正文内容

一、pandas是什么?

示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

二、代码结构

1.介绍主html代码

代码如下:

<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>2023新年快乐</title>
</head>

<body>

<script src='js/gameCanvas-4.0.js'></script>
<script src="js/script.js"></script>

<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;
</body>

</html>

可以看到引入了两个js文件,也同样在本地。 

2. js文件介绍

代码如下:

GameCanvas.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 points中包裹的文本可以改变烟花爆炸时出现的文字


var gc = new GameCanvas();

var points = textToPoints(" 2023新年快乐!", 15, "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;
}

运行效果

光说不练假把式,看图:

运行效果如下

 


总结

以上就是今天要讲的内容,本文介绍了跨年烟花代码使用。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/185048.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

css3-动画

目录语法转换平移旋转缩放复合属性的顺序问题过渡动画帧动画案例案例1-热点图dot(缩放)案例2-热点图dot(缩放)案例3-开红包(旋转)问题问题1-transform不起作用问题2 - 过渡动画不起效果语法 转换 css3中的转换允许我们对元素进行旋转、缩放、移动或倾斜。它分为2D转换 或 3D转…

开箱即用的物联网平台-IoTLink

物联网平台是物联网生态系统的重要组成部分&#xff0c;也是一个快速增长的市场&#xff0c;物联网平台为企业提供了巨大的价值&#xff0c;使他们能够降低开发成本、加速启动和简化流程。 一个完整的物联网系统需要硬件、连接、软件、用户界面等。在较高的层面上&#xff0c;…

menuconfig的执行过程

menuconfig &#xff08;1&#xff09;首先在uboot源码顶层目录下的Makefile文件中查找config&#xff08;%表示省略&#xff09; &#xff08;2&#xff09;执行make menuconfig&#xff0c;分别打印输出$(MAKE)、$(bulid)、$可知其对应的内容&#xff0c;如上图所示 总结&a…

用docker部署django后台作为webstack的后台管理系统-其二

0 序言 在之前的博客中&#xff1a; 用docker部署webstack导航网站-其一https://blog.csdn.net/qq_41938259/article/details/128736551?spm1001.2014.3001.5501我成功的将webstack官方推荐的docker容器部署了出来&#xff0c;但是官方的docker容器后端使用的是PHP&#xff0…

08_FreeRTOS列表和列表项讲解

目录 列表和列表项的简介 列表 列表项 迷你列表项 列表和列表项的关系 列表相关API函数介绍 初始化列表vListInitialise函数详解 列表项的初始化函数vListInitialiseItem函数 列表项的插入vListInsert函数 列表项末尾插入vListInsertEnd函数 列表项的删除函数uxLis…

零入门容器云网络实战-5->路由知识总结

本篇文章主要用于收集、整理、总结路由相关知识点。 1、路由分为几种&#xff1f; 直连路由静态路由&#xff08;基本静态路由&#xff0c;等价静态路由&#xff0c;活动静态路由&#xff0c;缺省静态路由&#xff09;动态路由 通过路由协议从相邻路由器学习到的。路由协议&am…

一,SpringMVC入门

0 MVC设计模式 View&#xff08;视图&#xff09;&#xff1a;页面&#xff08;jsp、html&#xff09;&#xff0c;接收用户数据和显示结果。 Controller&#xff08;控制器&#xff09;&#xff1a;action&#xff0c;接收请求&#xff0c;决定程序执行流程。 Model&#xf…

【深度学习】——循环神经网络RNN及实例气温预测

引言 密集连接网络和卷积神经网络都有主要的特点&#xff0c;那就是它们没有记忆。它们单独处理每个输入&#xff0c;在输入和输入之间没有保存任何状态。举个例子&#xff1a;当你在阅读一个句子的时候&#xff0c;你需要记住之前的内容&#xff0c;我们才能动态的了解这个句子…

三、SqlSession的创建以及执行流程

简介 SqlSession接口提供了查询&#xff0c;插入&#xff0c;更新&#xff0c;删除方法&#xff0c;Mybatis中所有的数据库交互都由SqlSession来完成。SqlSession 对象完全包含以数据库为背景的所有执行 SQL 操作的方法&#xff0c;它的底层封装了 JDBC 连接&#xff0c;可以用…

微服务链路追踪SkyWalking学习笔记

目录 1、skywalking是什么 1.2 链路追踪框架对比 1.3 性能对比 1.4 Skywalking主要功能特性 2、 SkyWalking 环境搭建部署 2.1 下载 SkyWalking 2.2 搭建SkyWalking OAP 服务 2.3 SkyWalking中三个概念 3、 SkyWalking 接入微服务 3.1 linux环境—通过jar包方式接入 …

SAP ADM100-2.5 系统启动:日志文件

本节将介绍SAP ABAP系统启动时最重要的log文件和Trce文件,以掌握通过使用系统启动log文件和trace文件分析系统问题。 1、记录系统启动过程 启动过程是一个特别重要的阶段,因此该过程将被操作系统、SAP系统、数据库记录。如果SAP系统没有启动,那么你将在log日志文件中发现相…

C#使用IronPython调用Python

一、前言以下摘自百度百科&#xff1a;IronPython 是一种在 NET 和 Mono 上实现的 Python 语言&#xff0c;由 Jim Hugunin&#xff08;同时也是 Jython 创造者&#xff09;所创造。1.0 版于2006年9月5日发布。随后&#xff0c;在 2007 年&#xff0c;开发者决定改写架构&#…

音视频xxxx

文章目录前言编解码硬件解码(高级)软解码(低级)软、硬解码对比视频解码有四个步骤Android 系统中编解码器的命名方式查看当前设备支持的硬解码基础知识RGB色彩空间常见的格式对比YUV索引格式分离RGB24像素数据中的R、G、B分量BMP 文件格式格式组成像素排列顺序RGB24格式像素数据…

Apache Solr 9.1-(三)集群模式下通过Http API操作Apache Solr

Apache Solr 9.1-&#xff08;三&#xff09;集群模式下通过Http API操作Apache Solr Solr是一个基于Apache Lucene的搜索服务器&#xff0c;Apache Lucene是开源的、基于Java的信息检索库&#xff0c;Solr能为用户提供无论在任何时候都可以根据用户的查询请求返回结果&#xf…

网络原理(TCP/IP)(3)

4)滑动窗口 1)咱们滑动窗口的效果就是说在我们尽可能地保证可靠性的情况下&#xff0c;尽可能的提高传输效率2)况且咱们进行发送滑动窗口的本质就是说进行批量的发送数据&#xff0c;咱们尽可能说是把等待ACK的时间总体进行缩短&#xff0c;咱们可以把等待一份ACK的时间变成等待…

凸优化学习:PART1凸集

凸优化学习PART1 一、引言&#xff1a;优化问题简介 优化问题的定义 凸优化是优化的一种&#xff0c;是优化中比较容易的问题。在讲解优化问题前&#xff0c;首先说明什么是优化/数学规划&#xff08;Optimization/Mathematical Planning&#xff09;。 优化&#xff1a;从一…

搭建electron开发环境

electron是使用js,html,css构建桌面端应用程序的框架&#xff0c;可以使用electron开发Windows和Mac端应用。 安装nodejs,npm,cnpm 首先需要安装nodejs,npm和cnpm&#xff0c;安装后在命令行输入 node -v 和npm -v&#xff0c;如果输出了版本号&#xff0c;说明已经正常安装。…

数据仓库-数据模型建设方法总结(全)

一、大数据领域建模综述 1.1 为什么需要数据建模 有结构地分类组织和存储是我们面临的一个挑战。 数据模型强调从业务、数据存取和使用角度合理存储数据。 数据模型方法&#xff0c;以便在性能、成本、效率之间取得最佳平衡 成本&#xff1a;良好的数据模型能极大地减少不必…

MyBatis:批量添加记录

MyBatis&#xff0c;一款优秀的ORM映射框架&#xff0c;可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO&#xff08;Plain Old Java Objects&#xff0c;普通老式 Java 对象&#xff09;为数据库中的记录。同时&#xff0c;MyBatis提供了动态SQL特性&#x…

梦熊杯-十二月月赛-白银组题解-C.永恒

C. Problem C.永恒&#xff08;eternity.cpp&#xff09; 内存限制&#xff1a;256 MiB 时间限制&#xff1a;1000 ms 标准输入输出 题目类型&#xff1a;传统 评测方式&#xff1a;文本比较 题目描述: 「稻妻」是「永恒」的国度。 巴尔泽布认为&#xff0c;如果一个数…