vue3实现反方向的钟

363 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情

穿梭时间的画面的钟 从反方向 开始移动

实现效果

chrome-capture-2022-5-16.gif

实现思路

1.完成时钟时针、分针、秒针、数字的布局

2.完成时钟顺时针旋转逻辑

3.完成时钟逆时针旋转逻辑

时钟时针、分针、秒针、数字的布局

创建一个容器盒子作为时钟。时针、分针、秒针绝对定位到时钟容器的中心就行。定位的top值应该是父盒子高度的一半。接着是12个数字的布局,这12个数字需要绝对定位父盒子top下面点,然后用transform-origin属性扩散到四周。你也可以使用rotateZ属性来写。直接用v-for循环遍历出来。然后旋转角度是索引值*30就行。

完成时钟顺时针旋转逻辑

使用setInterval定时器,使用new Date获取当前的时间,然后用getSeconds、getMinutes、getHours获取秒,分,时时间,并分别计算出要旋转的角度。然后使用ref获取元素使其旋转该角度就可以完成时间时针,分针,秒针的转动。时针应该是一小时旋转30度,分针一分钟6度,秒针一秒钟6度。

完成时钟逆时针旋转逻辑

获取当前的时间的时、分、秒,使用setInterval定时器,秒针每次-1,如果减60秒,分钟减一,分钟减60分钟,时针减一。就可以完成时钟倒转

部分代码

<script>
import { reactive, toRefs, getCurrentInstance,onMounted,nextTick  } from "vue";
export default {
  components: {},
  setup() {
    const state = reactive({
      h:0,
      m:0,
      s:0,
      sCount: 0,
      mCount: 0
    });
    const { ctx } = getCurrentInstance()
    let now = new Date()
    state.s = now.getSeconds()
    state.m = now.getMinutes()
    state.h = now.getHours()
    onMounted(()=>{
      ctx.$refs.hour.style.transform  = `rotate(${state.h*30 + 180}deg)`
      ctx.$refs.minutes.style.transform  = `rotate(${state.m*6 + 180}deg)`
      ctx.$refs.second.style.transform  = `rotate(${state.s*6 + 180}deg)`
      setInterval(()=>{
      clock()
    },10)
    })

    const clock = () => {
      state.s -= 1
      state.sCount++
      if(state.sCount >= 60){
        state.m = state.m - 1
        state.sCount = 0
        state.mCount++
      }
      if(state.mCount >= 60){
        if(state.h -= 1 >= 0){
          state.h -= 1
        } else {
          state.h = 23
        }
        state.mCount = 0
      }
      nextTick(()=>{
        ctx.$refs.hour.style.transform  = `rotate(${state.h*30 + 180}deg)`
        ctx.$refs.minutes.style.transform  = `rotate(${state.m*6 + 180}deg)`
        ctx.$refs.second.style.transform  = `rotate(${state.s*6 + 180}deg)`
      })
    }
    return {
      ...toRefs(state),
      clock
    };
  },
};
</script>

总结

  • 如何获取小时、分钟、秒
  • transform-origin、transform属性的使用
  • setInterval定时器的使用