こちらは、要素を中央に配置し、アニメーションを実行し、アニメーションが終了すると1.5秒待ってからアニメーションを再開する簡単なアニメーションのデモです。
HTML (index.html):
HTMLドキュメントの基本的な構造を定義しています。
<meta charset="UTF-8"> は文字エンコーディングを指定し、<meta name="viewport" content="width=device-width, initial-scale=1.0"> はモバイルデバイスに対応するためのビューポート設定です。
<link rel="stylesheet" href="style.css"> は外部のCSSファイル(style.css)を読み込んでいます。
<div id="dami-box"> と <div id="animated-element"></div> はアニメーションのためのHTML要素です。
<script src="script.js"></script> は外部のJavaScriptファイル(script.js)を読み込んでいます。このファイルにアニメーションのロジックが記述されています。
CSS (style.css):
#dami-box セレクタは、display: flex; justify-content: center; を設定して、子要素(#animated-element)を水平方向に中央に配置します。
#animated-element セレクタは、アニメーションの対象である要素のスタイルを指定しています。背景色が青で、サイズが100px × 100px、position: absolute; で配置されます。
JavaScript (script.js):
const element = document.getElementById('animated-element'); はHTML内の #animated-element 要素を取得し、element 変数に格納しています。
let startTime; はアニメーションの開始時刻を格納する変数です。
animate(timestamp) 関数は requestAnimationFrame を使用してアニメーションを実行します。アニメーションは回転します。
timestamp パラメータは requestAnimationFrame によって提供され、アニメーションのタイミングを制御します。
startTime が初めて設定された場合、アニメーションの開始時刻を記録します。
経過時間を計算し、進捗度合いを算出して、要素の回転角度を設定します。
アニメーションが完了していない場合は、再び requestAnimationFrame(animate) を呼び出して次のフレームを要求します。
アニメーションが完了したら、setTimeout を使用して1.5秒後にアニメーションを再開します。startTime をリセットしてから再度 requestAnimationFrame(animate) を呼び出すことで、アニメーションをループさせます。
最終的に、このコードは要素を中央に配置し、アニメーションを実行し、アニメーションが終了すると1.5秒待ってからアニメーションを再開する簡単なアニメーションのデモです。
コード
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animation Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<br>
<div id="dami-box">
<div id="animated-element"></div>
</div>
<br>
<script src="script.js"></script>
</body>
</html>
#dami-box {
display: flex;
justify-content: center;
}
#animated-element {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
}
const element = document.getElementById('animated-element');
let startTime;
function animate(timestamp) {
if (!startTime) {
startTime = timestamp;
}
const elapsedTime = timestamp - startTime;
const progress = elapsedTime / 2000;
element.style.transform = `rotate(${360 * progress}deg)`;
if (progress < 1) {
requestAnimationFrame(animate);
} else {
setTimeout(() => {
startTime = null;
requestAnimationFrame(animate);
}, 1500);
}
}
requestAnimationFrame(animate);
