<!DOCTYPE html>
<html>
  <head>
    <title>一群鱼在水里游</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas"></canvas>
<pre><code>&lt;script&gt;
  const canvas = document.getElementById(&quot;myCanvas&quot;);
  const ctx = canvas.getContext(&quot;2d&quot;);

  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  const fishImg = new Image();
  fishImg.src = &quot;https://i.imgur.com/7XU6kAa.png&quot;;

  let fishArray = [];

  class Fish {
    constructor(x, y, speed, size) {
      this.x = x;
      this.y = y;
      this.speed = speed;
      this.size = size;
      this.frameX = 0;
      this.frameY = 0;
      this.spriteWidth = 440;
      this.spriteHeight = 440;
    }

    update() {
      this.x -= this.speed;
      if (this.x &lt; -100) {
        this.x = canvas.width + 100;
        this.y = Math.random() * (canvas.height - 200) + 100;
        this.speed = Math.random() * 5 + 1;
      }
      this.frameX = (this.frameX + 1) % 8;
    }

    draw() {
      ctx.drawImage(
        fishImg,
        this.frameX * this.spriteWidth,
        this.frameY * this.spriteHeight,
        this.spriteWidth,
        this.spriteHeight,
        this.x,
        this.y,
        this.size,
        this.size
      );
    }
  }

  function init() {
    for (let i = 0; i &lt; 20; i++) {
      let size = Math.random() * 50 + 50;
      let x = Math.random() * canvas.width;
      let y = Math.random() * (canvas.height - 200) + 100;
      let speed = Math.random() * 5 + 1;
      let fish = new Fish(x, y, speed, size);
      fishArray.push(fish);
    }
  }

  function animate() {
    requestAnimationFrame(animate);
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (let i = 0; i &lt; fishArray.length; i++) {
      fishArray[i].update();
      fishArray[i].draw();
    }
  }

  init();
  animate();
&lt;/script&gt;
</code></pre>
  </body>
</html>
写一个 一群鱼在水里游的html5

原文地址: https://www.cveoy.top/t/topic/0ml 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录