生成AI+スマホで作成「WordPress(ブログ)で使えるJavaScript」 画像の上に舞う桜の花びら

コードエディター 本文

<canvas id="sakuraCanvas"></canvas>

カスタムJavaScript

    const canvas = document.getElementById('sakuraCanvas');
    const ctx = canvas.getContext('2d');

    function resize() {
        canvas.width = 320; // window.innerWidth;
        canvas.height = 240; // window.innerHeight;
    }
    window.addEventListener('resize', resize);
    resize();

    const petals = [];
    const petalCount = 100;

    class Petal {
        constructor() {
            this.init();
        }

        init() {
            this.x = Math.random() * canvas.width;
            this.y = Math.random() * canvas.height - canvas.height;
            this.size = Math.random() * 8 + 4; 
            this.speed = Math.random() * 2 + 0.5;
            this.angle = Math.random() * 360;
            this.spin = Math.random() * 2 - 1;
            this.wind = Math.random() * 1.5 - 0.5;
            this.opacity = Math.random() * 0.6 + 0.3; // 透明度のバラつき
        }

        draw() {
            ctx.save();
            ctx.translate(this.x, this.y);
            ctx.rotate(this.angle * Math.PI / 180);
            ctx.globalAlpha = this.opacity;

            // グラデーションの作成
            const grad = ctx.createRadialGradient(0, 0, 0, 0, 0, this.size);

            // 花びらの色を画像に合わせる 
            grad.addColorStop(0, '#ffffff');    // 中心(白)
            grad.addColorStop(0.2, '#e1d2ff');  // 中間 #ffdbed (淡いピンク)
            grad.addColorStop(1, '#dfcffe');    // 外側 #ffb7c5 (桜色)

            ctx.beginPath();
            // ハートに近い、少し切り込みのある花びらの形
            ctx.moveTo(0, 0);
            ctx.bezierCurveTo(-this.size, -this.size, -this.size, this.size/2, 0, this.size);
            ctx.bezierCurveTo(this.size, this.size/2, this.size, -this.size, 0, 0);
            
            ctx.fillStyle = grad;
            ctx.fill();
            ctx.restore();
        }

        update() {
            this.y += this.speed;
            this.x += this.wind;
            this.angle += this.spin;

            if (this.y > canvas.height + 20) {
                this.init();
                this.y = -20;
            }
        }
    }

    for (let i = 0; i < petalCount; i++) {
        petals.push(new Petal());
    }

    // サイズでソートして重なり(遠近感)を表現
    petals.sort((a, b) => a.size - b.size);

    function animate() {
        // 背景画像が見えるように透過してクリア
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        petals.forEach(petal => {
            petal.update();
            petal.draw();
        });
        requestAnimationFrame(animate);
    }

    animate();       

カスタムCSS

#sakuraCanvas{
    background-image: url('https://blog.sikigaku.net/wp-content/uploads/2026/01/f81fd2e4c52864042852c112ce927ae2.jpeg');
    background-size: cover; /* キャンバス全体を覆うように調整 */
    background-position: center;
  }