JavsScriptでアナログ時計を作成

✏️️ 2019/08/17 👍️2019/08/17 🔗

Sample Code

<div class="clock">
  <div class="lineHour"></div>
  <div class="lineMin"></div>
  <div class="lineSec"></div>
</div>
.clock {
  border-radius: 50%;
  border: 3px solid gray;
  width: 100px;
  height: 100px;
  position: relative;

  .lineHour {
    width: 5px;
    height: 38px;
    background: gray;
    position: absolute;
    top: calc(50% - 38px);
    left: calc(50% - 5px);
    transform-origin: bottom;
  }

  .lineMin {
    width: 3px;
    height: 50px;
    background: gray;
    position: absolute;
    top: calc(50% - 50px);
    left: calc(50% - 2px);
    transform-origin: bottom;
  }

  .lineSec {
    width: 2px;
    height: 50px;
    background: gray;
    position: absolute;
    top: calc(50% - 50px);
    left: calc(50% - 1px);
    transform-origin: bottom;
  }
}
    setInterval(() => {
        const now = new Date();
        const h = now.getHours();
        const m = now.getMinutes();
        const s = now.getSeconds();

        const degH = h * (360 / 12) + m * (360 / 12 / 60);
        const degM = m * (360 / 60);
        const degS = s * (360 / 60);

        const elementH = document.querySelector('.lineHour');
        const elementM = document.querySelector('.lineMin');
        const elementS = document.querySelector('.lineSec');

        elementH.style.transform = `rotate(${degH}deg)`;
        elementM.style.transform = `rotate(${degM}deg)`;
        elementS.style.transform = `rotate(${degS}deg)`;
    }, 100);

Akito
日本のスタートアップで主にRuby on Railsを使ってプロダクト開発をしています。