专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

WEB前端手写时钟-指针角度逻辑 js写时钟

ins518 2024-10-09 16:25:14 技术文章 12 ℃ 0 评论

上回我们把主要结构写好了,今天我们把指针旋转逻辑实现了,下面我们就用JS代码实现。

主要内容:

  1. 在Date的原型上添加相关方法
  2. 利用添加的方法获取时分秒微秒数
  3. 将指针数转换为角度(84行)

经过下面的封装使用也是非常方便:

consg now = new Date;
const angle = now.getAngle();

// 示例时间 19:05:35
/*
结果为 {
    "s": 213.20999999999998,
    "m": 33.5535,
    "h": 572.796125,  // 此处角度多了360度 不影响观感
}
*/
/** 处理日期类方便后面使用 */
(function () {
    /**
     * JS自带的获取小时方法
     * @type {int}
     */
    const getHour = Date.prototype.getHours;
    /**
     * JS自带的获取分钟方法
     * @type {int}
     */
    const getMinute = Date.prototype.getMinutes;
    /**
     * 系统自带的获取秒的方法
     * @type {int}
     */
    const getSecond = Date.prototype.getSeconds;
    /**
     * 系统自带的获取月份的方法
     * @type {int}
     */
    const getMonth = Date.prototype.getMonth;
    /**
     * 整数的小于10 前面填充0 大于9则不变
     * @param  {int} num 待处理的整数
     * @return {string}  处理好的数据转换为字符串
     */
    const fillZero = function (num) {
        if(num < 10) {
            return '0' + num;
        }
        return '' + num;
    }

    /**
     * 覆盖系统日期类原型上的获取小时的方法
     * @return {string} 当前时间的小时
     */
    Date.prototype.getHours = function() {
        return fillZero(getHour.bind(this)());
    };

    /**
     * 覆盖系统日期类原型上的获取分钟的方法
     * @return {string} 当前时间的分钟数
     */
    Date.prototype.getMinutes = function() {
        return fillZero(getMinute.bind(this)());
    };

    /**
     * 覆盖系统日期类原型上的获取秒的方法
     * @return {string} 当前时间的秒数
     */
    Date.prototype.getSeconds = function() {
        return fillZero(getSecond.bind(this)());
    };

    /**
     * 覆盖系统日期类原型上的获取月份的方法
     * @return {string} 当前时间的月份
     */
    Date.prototype.getMonth = function () {
        let m = getMonth.call(this);
        return fillZero(m + 1);
    };

    /**
     * 覆盖系统日期类原型上的获取微秒的方法
     * @return {string} 当前时间的微秒数
     */
    Date.prototype.getMicroSeconds = function () {
        let t = this.getTime();
        return (''+t).slice(-3) / 1000;
    }

    /**
     * 给系统自带日期类添加获取当前日期角度的方法 (角度值)
     * @return {object} 当前时间时分秒指针对应的角度
     * h:时针对应的角度
     * m:分针对应的角度
     * s:秒针对应的角度
     */
    Date.prototype.getAngle = function () {
        let micrs = this.getMicroSeconds();
        let s = getSecond.call(this);
        s = (s+micrs) * 6;
        let m = getMinute.call(this);
        m = m * 6 + s * 6/360;
        let h = getHour.call(this);
        h = h * 30 + ((m * 30)/360);
        return {s,m,h};
    };

    Date.prototype.getDateTime = function () {
        return `${this.getFullYear()}/
                ${this.getMonth()}/
                ${fillZero(this.getDate())}
                 ${this.getTimes()}`;
    };

    Date.prototype.getTimes = function () {
        return `${this.getHours()}:
                ${this.getMinutes()}:
                ${this.getSeconds()}`;
    };
} ());

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表