クリック地点から円が広がるエフェクトを紹介します。
クリックされた位置を取得し、その位置から円が徐々に広がるアニメーションを適用します。2秒後にこの円はフェードアウトし、完全に消えます。
ただ、アニメーションを繰り返す際に問題が発生することがあります。特にCSSのtransformトランジションの再適用はブラウザによってはうまく動作しないことがあります。この問題を回避するために、円要素をDOMから削除して再作成しています。これにより、何度でも再生されます。
※サンプルはこちら
HTML
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>円の広がり効果</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div id="container" onclick="expandCircle(event)"> <div id="circle"></div> </div> <script src="script.js"></script> </body> </html>
CSS(style.css)
body, html { height: 100%; margin: 0; overflow: hidden; } #container { width: 100%; height: 100%; position: relative; } #circle { position: absolute; width: 50px; height: 50px; background-color: rgba(0, 0, 0, 0.6); border-radius: 50%; transform-origin: center; transform: scale(0); pointer-events: none; transition: transform 1s; /* animation duration can be adjusted */ } #circle { /* ... その他のスタイル ... */ opacity: 1; transition: transform 1s, opacity 1s; /* opacityのアニメーションを追加 */ pointer-events: none; // 確実に親要素(container)がクリックイベントを受け取る }
Javascript(script.js)
function expandCircle(event) { const circle = document.getElementById('circle'); const maxSize = Math.sqrt(window.innerWidth**2 + window.innerHeight**2) * 2; const scaleSize = maxSize / 50; // circle's original size is 50px circle.style.left = `${event.clientX - 25}px`; // 25 is half of circle's original size circle.style.top = `${event.clientY - 25}px`; circle.style.transform = `scale(${scaleSize})`; } // 要素の再描画のためのヘルパー関数 function forceReflow(element) { element.offsetHeight; // reflowをトリガー } function expandCircle(event) { const container = document.getElementById('container'); let circle = document.getElementById('circle'); // 円をDOMから削除 container.removeChild(circle); // 新しい円要素を作成 circle = document.createElement('div'); circle.id = 'circle'; // 新しい円をコンテナに追加 container.appendChild(circle); const maxSize = Math.sqrt(window.innerWidth**2 + window.innerHeight**2) * 2; const scaleSize = maxSize / 50; circle.style.opacity = '1'; circle.style.transform = `scale(0)`; circle.style.left = `${event.clientX - 25}px`; circle.style.top = `${event.clientY - 25}px`; setTimeout(() => { circle.style.transform = `scale(${scaleSize})`; setTimeout(() => { circle.style.opacity = '0'; }, 100); }, 10); }