生成AI+スマホで作成「WordPress(ブログ)で使えるJavaScript」 タップでキラキラ

コードエディター 本文

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

カスタムJavaScript

    const handleEvent = (e) => {
        const clientX = e.touches ? e.touches[0].pageX : e.pageX;
        const clientY = e.touches ? e.touches[0].pageY : e.pageY;
        
        // 1回のタップで10個の星を生成
        for (let i = 0; i < 10; i++) {
            createStar(clientX, clientY);
        }
    };

    document.addEventListener('touchstart', handleEvent);
    document.addEventListener('mousedown', handleEvent);

    function createStar(x, y) {
        const star = document.createElement('div');
        star.className = 'star';
        
        // 星の形をランダムに選ぶ(お好みで増やせます)
        const shapes = ['★', '☆', '✧', '✦'];
        star.innerHTML = shapes[Math.floor(Math.random() * shapes.length)];
        
        // 色をランダムに設定
        const colors = ['#ffd700', '#ffffff', '##ffc9d2', '#00ffff', '#ffff00', '#fd951e'];
        star.style.color = colors[Math.floor(Math.random() * colors.length)];
        
        // サイズをランダムに設定 (7px 〜 22px)
        const size = Math.floor(Math.random() * 15) + 7;
        star.style.fontSize = `${size}px`;

        // アニメーション時間をランダムに設定 (0.5秒 〜 1.2秒)
        const duration = Math.random() * 0.7 + 0.5; star.style.animationDuration = `${duration}s`;

        // 飛び散る距離をランダムに計算 (-100px 〜 100px)
        const tx = (Math.random() - 0.5) * 200;
        const ty = (Math.random() - 0.5) * 200;
        star.style.setProperty('--tx', `${tx}px`);
        star.style.setProperty('--ty', `${ty}px`);
        star.style.left = x + 'px';
        star.style.top = y + 'px';

        document.body.appendChild(star);

        // 設定したアニメーション時間が経過したら削除
        setTimeout(() => {
            star.remove();
        }, duration * 1000);
    }

カスタムCSS

    #canvas {
            background-color: #393e4f;
    }

    .star {
            position: absolute;
            pointer-events: none;
            user-select: none;
            font-size: 20px;
            /* 変化させる変数(JSから制御) */
            --tx: 0px;
            --ty: 0px;
            animation: explode 0.8s ease-out forwards;
    }

    /* 四方八方に飛び散るアニメーション */
    @keyframes explode {
            0% {
                transform: translate(-50%, -50%) scale(0) rotate(0deg);
                opacity: 1;
            }
            100% {
                /* JSで設定した移動距離(--tx, --ty)まで飛ばす */
                transform: translate(calc(-50% + var(--tx)), calc(-50% + var(--ty))) scale(1.2) rotate(360deg);
                opacity: 0;
            }
    }