生成AI+スマホで作成「WordPress(ブログ)で使えるJavaScript」 canvasに背景画像を入れる

ネタ帳にふさわしいくだらない画像ができた

コードエディター 本文

<canvas id="fireCanvas" width="320" height="460"></canvas>

カスタムJavaScript

(() => {
  const canvas = document.getElementById("fireCanvas");
  const ctx = canvas.getContext("2d");

  // キャンバス固定サイズ(CSSで中央寄せ)
  const CANVAS_WIDTH = 320;
  const CANVAS_HEIGHT = 460;

  // 背景画像
  const bgImage = new Image();
  bgImage.src = "背景画像.jpeg"; // 背景画像パス
  let bgLoaded = false;
  bgImage.onload = () => { bgLoaded = true; };

  // 背景の描画位置とサイズ(固定キャンバス内座標)
  const bgPosX = 0;   // 左から100px
  const bgPosY = 0;    // 上から50px
  const bgWidth = 320; // 幅
  const bgHeight = 460; // 高さ

  // 炎の発生ポイント(固定キャンバス内座標)
  const firePoints = [
    { x: 164, y: 231 }, // 1つ目の炎の位置
//    { x: 90, y: 200 }  // 予備用 2つ目の炎の位置
  ];

  // 炎パーティクルクラス
  class Particle {
    constructor(x, y) {
      this.x = x;
      this.y = y;
      this.size = Math.random() * 20 + 10;
      this.speedY = Math.random() * -2 - 1;
      this.speedX = (Math.random() - 0.5) * 1;
      this.life = Math.random() * 60 + 40;
      this.opacity = 1;
      this.hue = Math.random() * 30; // 赤〜黄
    }
    update() {
      this.x += this.speedX;
      this.y += this.speedY;
      this.life--;
      this.opacity = this.life / 100;
      this.size *= 0.96;
    }
    draw(ctx) {
      ctx.beginPath();
      ctx.fillStyle = `hsla(${this.hue}, 100%, 50%, ${this.opacity})`;
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      ctx.fill();
    }
  }

  const particles = [];

  function animate() {
    // 背景描画(位置とサイズ指定)
    if (bgLoaded) {
      ctx.drawImage(bgImage, bgPosX, bgPosY, bgWidth, bgHeight);
    } else {
      ctx.fillStyle = "#000";
      ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    }

    // 半透明で残像効果
    ctx.fillStyle = "rgba(0, 0, 0, 0.2)";
    ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    // 各炎ポイントでパーティクル生成
    firePoints.forEach(point => {
      for (let i = 0; i < 3; i++) {
        particles.push(new Particle(point.x, point.y));
      }
    });

    // パーティクル更新&描画
    for (let i = particles.length - 1; i >= 0; i--) {
      const p = particles[i];
      p.update();
      p.draw(ctx);
      if (p.life <= 0 || p.size < 0.5) {
        particles.splice(i, 1);
      }
    }

    requestAnimationFrame(animate);
  }

  animate();
})();


カスタムCSS

 /* WordPress cocoon でbodyは弄らない */
 /* body {
    background: black;
    margin: 0;
    overflow: hidden;
    display: flex;
    justify-content: center; /* 中央寄せ */
    align-items: center;
    height: 100vh;
  }*/
  canvas {
    display: block;
    background: #000;
    border: 2px solid #444;
  }