JavaScriptのきほん「ブラウザで時計を表示しよう(1)」

スポンサーリンク
パソコン JavaScript

今回は、ブラウザで「アナログ時計・デジタル時計・カレンダー」を表示するHTML+Javascriptをご紹介しよう。
各構成は以下の通りとなる。

🏗️ HTML構造

<div class="clock" id="analog-clock">

  <div class="hand hour" id="hour"></div>

  <div class="hand minute" id="minute"></div>

  <div class="hand second" id="second"></div>

</div>

<div id="digital-clock">--:--:--</div>

<div id="calendar">----年--月--日(--)</div>

#analog-clock: 円形のアナログ時計(針は短針、長針、秒針の3本)

#digital-clock: デジタル時計

#calendar: 今日の日付(和暦形式)

🎨 スタイル(CSS)

時計と針の見た目を定義している。

アナログ時計

  • .clock: 円形、白背景、枠線あり
  • .hand: 共通の針スタイル(位置・中心を基点に回転)
  • .hour, .minute, .second: 各針の幅・長さ・色を指定

時計の数字

  • .number: 1~12の数字を円周に配置

デジタル時計・カレンダー

  • 白背景・影付きのボックス
  • フォントサイズ・色が調整済み

🧠 ロジック(JavaScriptファイル)

1. pad(num)

数字を2桁に整形(例: 5 → 05)

2. getJapaneseWeekday(dayIndex)

曜日番号を日本語(例: 日, 月, …)に変換

3. updateClock()

毎秒実行されるメイン関数

  • 現在の時刻を取得
  • アナログ時計の針を回転(角度計算)
  • デジタル時計の表示更新
  • カレンダーの日付と曜日を更新

角度の計算式例

const hourDeg = ((hours % 12) + minutes / 60) * 30;

12時間を360度に割り、分単位で補正(滑らかに動く)

4. createClockNumbers()

時計の文字盤に1~12の数字を配置

  • 円周上に div を配置(角度と半径を使って座標計算)
const angle = (i * 30 - 90) * (Math.PI / 180); // 12時を上にする調整

5. 実行部分

createClockNumbers();

setInterval(updateClock, 1000);

updateClock(); // 初期表示
  • 数字の配置を生成
  • 毎秒 updateClock() を呼び出す

💡 特徴・工夫点

  • CSSのみで時計の針を表現(画像は不使用)
  • 時計の針がリアルタイム滑らかに回転する
  • カレンダーは曜日を日本語で表記する
  • レスポンシブなデザイン(中央揃え、全画面対応)

以下に、このプログラムファイルをご紹介しよう。

HTMLファイル(Analog_and_digital_clocks.html)

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>アナログ&デジタル時計+カレンダー</title>
  <style>
    body {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
      background-color: #f0f0f0;
      font-family: sans-serif;
    }

    .clock {
      width: 300px;
      height: 300px;
      border: 10px solid #333;
      border-radius: 50%;
      position: relative;
      background: white;
    }

    .hand {
      position: absolute;
      left: 50%;
      bottom: 50%;
      transform-origin: bottom center;
    }

    .hour {
      width: 6px;
      height: 70px;
      background: black;
      z-index: 3;
    }

    .minute {
      width: 4px;
      height: 90px;
      background: gray;
      z-index: 2;
    }

    .second {
      width: 2px;
      height: 100px;
      background: red;
      z-index: 1;
    }

    .number {
      position: absolute;
      width: 30px;
      height: 30px;
      text-align: center;
      font-size: 20px;
      font-weight: bold;
      color: #333;
      transform: translate(-50%, -50%);
    }

    #digital-clock, #calendar {
      margin-top: 20px;
      font-size: 24px;
      font-weight: bold;
      background: white;
      padding: 10px 20px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0,0,0,0.2);
    }

    #calendar {
      font-size: 18px;
      margin-top: 10px;
      color: #555;
    }
  </style>
</head>
<body>
  <div class="clock" id="analog-clock">
    <div class="hand hour" id="hour"></div>
    <div class="hand minute" id="minute"></div>
    <div class="hand second" id="second"></div>
  </div>
  <div id="digital-clock">--:--:--</div>
  <div id="calendar">----年--月--日(--)</div>
     <script src ="script.js"> </script>
  </body>
</html>

JavaScriptファイル(script.js)

function pad(num) {
    return num.toString().padStart(2, '0');
  }

  function getJapaneseWeekday(dayIndex) {
    const weekdays = ['日', '月', '火', '水', '木', '金', '土'];
    return weekdays[dayIndex];
  }

  function updateClock() {
    const now = new Date();

    const hours = now.getHours();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds();

    const hourDeg = ((hours % 12) + minutes / 60) * 30;
    const minuteDeg = (minutes + seconds / 60) * 6;
    const secondDeg = seconds * 6;

    document.getElementById('hour').style.transform = `rotate(${hourDeg}deg)`;
    document.getElementById('minute').style.transform = `rotate(${minuteDeg}deg)`;
    document.getElementById('second').style.transform = `rotate(${secondDeg}deg)`;

    const digital = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
    document.getElementById('digital-clock').textContent = digital;

    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const date = now.getDate();
    const weekday = getJapaneseWeekday(now.getDay());

    document.getElementById('calendar').textContent = `${year}年${month}月${date}日(${weekday})`;
  }

  function createClockNumbers() {
    const clock = document.getElementById('analog-clock');
    const centerX = 150;
    const centerY = 150;
    const radius = 130;

    for (let i = 1; i <= 12; i++) {
      const angle = (i * 30 - 90) * (Math.PI / 180);
      const x = centerX + radius * Math.cos(angle);
      const y = centerY + radius * Math.sin(angle);

      const numDiv = document.createElement('div');
      numDiv.className = 'number';
      numDiv.style.left = `${x}px`;
      numDiv.style.top = `${y}px`;
      numDiv.textContent = i;

      clock.appendChild(numDiv);
    }
  }

  createClockNumbers();
  setInterval(updateClock, 1000);
  updateClock(); // 初期表示

実行結果

アナログ時計・デジタル時計・カレンダー

コメント

タイトルとURLをコピーしました