JavaScipt30(第二个案例)

承接上篇https://www.cnblogs.com/wangxi01/p/10641115.html,这是第二个案例

附上项目链接: https://github.com/wesbos/JavaScript30

这是要实现一个钟表的效果。下面是他的源码,我进行了一些注释。最开始我自己写的时候被一个东西卡住了,我知道钟表的旋转用rotate来实现,但是旋转的中心点不在钟表的中心,

我有点束手无策,大概猜到会有调整中心点的属性,不过没去查看,直接查看了源码。

.hand {
     50%;
    height: 6px;
    background: black;
    position: absolute;
    top: 50%;
    /* 更改转换元素的位置,以达到中心点在钟表的中心 */
    transform-origin: 100%;
    transform: rotate(90deg);
    transition: all 0.05s;
    /* 指定切换效果的速度 cubic-bezier贝塞尔曲线,我查了一下,他好像是有个公式的,四个参数分别为x1,y1,x2,y2,单从数值上好像看不出快慢的规律*/
    transition-timing-function: cubic-bezier(0.1, 2.7, 0.58, 1);
}
const secondHand = document.querySelector('.second-hand');
const minsHand = document.querySelector('.min-hand');
const hourHand = document.querySelector('.hour-hand');

function setDate() {
    const now = new Date();
    // 得到当前秒数
    const seconds = now.getSeconds();
    // 得到正常在圆内的度数,因为初始旋转度数为90度,所以要加上90度
    const secondsDegrees = ((seconds / 60) * 360) + 90;
    secondHand.style.transform = `rotate(${secondsDegrees}deg)`;

    const mins = now.getMinutes();
    // 得到当前分钟在圆内的度数,再加上秒钟在钟表内一格所处的度数,一格为6度(360/(12*5))
    const minsDegrees = ((mins / 60) * 360) + ((seconds / 60) * 6) + 90;
    minsHand.style.transform = `rotate(${minsDegrees}deg)`;

    const hour = now.getHours();
    // 得到当前小时在圆内的度数,再加上分钟在小时钟表内一格所处的度数,一格为30度(360/12)
    const hourDegrees = ((hour / 12) * 360) + ((mins / 60) * 30) + 90;
    hourHand.style.transform = `rotate(${hourDegrees}deg)`;
}
// 每秒渲染一次
setInterval(setDate, 1000);

setDate();

备注:主要思路,拿到当前时分秒,算出它们在这一时刻分别所处的位置,渲染出来,后面定时器每秒重新渲染就可以了。

下一个案例: https://www.cnblogs.com/wangxi01/p/10641708.html

好记性不如烂笔头,看到自己觉得应该记录的知识点,结合自己的理解进行记录,用于以后回顾。
原文地址:https://www.cnblogs.com/wangxi01/p/10641210.html