Files
mouse-clock/mouse-clock.js
T

193 lines
8.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*!
* 滑鼠立體時鐘 Mouse Clock 1.1.0
* https://code.tsdylab.com/tangsongdayo/mouse-clock
*
* 原作:Silly Clock 3 by Kurt Grigg
* 中文化:網頁建置百寶箱 JavaScript 收集區
* 改寫:唐宋打油 https://tsdylab.com/(觸控支援、設定項、可停止)
* 授權說明見 LICENSE
*/
(function () {
'use strict';
var DEFAULTS = {
dateColor: '#000000', // 日期環顏色
faceColor: '#0000ff', // 鐘面數字顏色
hourColor: '#ff0000', // 時針顏色
minuteColor: '#0000ff', // 分針顏色
secondColor: '#00ff00', // 秒針顏色
size: 40, // 鐘面半徑(px)
offsetX: 80, // 時鐘中心在游標右邊多少 px(負值=左邊)
offsetY: 80, // 時鐘中心在游標下面多少 px(負值=上面)
touchOffsetX: 0, // 手機:時鐘中心相對手指的位置
touchOffsetY: -110, // 預設在手指上方,不會被手掌擋住
speed: 0.3, // 跟隨速度 0~1,越小拖得越長(原版 0.6)
dateSpeed: 0.015, // 日期環旋轉速度(原版 0.06)
lang: 'zh-TW', // 日期語言:'zh-TW' 或 'en'
zIndex: 9999,
reducedMotion: 'hide' // 使用者系統設定「減少動態」時:'hide' 不顯示、'show' 照常顯示
};
var NAMES = {
'zh-TW': {
days: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
format: function (y, mo, d, wd) { return y + '年 ' + mo + ' ' + d + '日 ' + wd + ' '; }
},
en: {
days: ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'],
months: ['JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER'],
format: function (y, mo, d, wd) { return ' ' + wd + ' ' + d + ' ' + mo + ' ' + y + ' '; }
}
};
var running = null;
function start(options) {
if (running) running.stop();
var o = {}, k;
for (k in DEFAULTS) o[k] = DEFAULTS[k];
for (k in (options || {})) if (options[k] !== undefined && options[k] !== '') o[k] = options[k];
['size', 'offsetX', 'offsetY', 'touchOffsetX', 'touchOffsetY', 'speed', 'dateSpeed', 'zIndex'].forEach(function (key) { o[key] = Number(o[key]); });
if (o.reducedMotion === 'hide' && window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
return null;
}
var names = NAMES[o.lang] || NAMES['zh-TW'];
var now = new Date();
var D = names.format(now.getFullYear(), names.months[now.getMonth()], now.getDate(), names.days[now.getDay()]).split('');
var H = '...'.split(''), M = '....'.split(''), S = '.....'.split('');
var Face = '1 2 3 4 5 6 7 8 9 10 11 12'.split(' ');
var n = Face.length, Split = 360 / n, Dsplit = 360 / D.length;
var R = o.size, HandLen = R / 4.5, HandY = -7, HandX = -2.5;
var xmouse = window.innerWidth / 2, ymouse = window.innerHeight / 2, currStep = 0;
var isTouch = !!(window.matchMedia && window.matchMedia('(hover: none)').matches);
function zeros(len) { var a = []; for (var i = 0; i < len; i++) a.push(0); return a; }
var y = zeros(n), x = zeros(n), Y = zeros(n), X = zeros(n);
var Dy = zeros(D.length), Dx = zeros(D.length), DY = zeros(D.length), DX = zeros(D.length);
var root = document.createElement('div');
root.className = 'mouse-clock';
root.setAttribute('aria-hidden', 'true');
var css = document.createElement('style');
css.textContent =
'.mouse-clock>div{position:fixed;top:0;left:0;pointer-events:none;text-align:center;line-height:1;' +
'will-change:transform;z-index:' + o.zIndex + ';margin:0;padding:0;}' +
'.mouse-clock .mc-face,.mouse-clock .mc-date{width:10px;height:10px;font:10px Arial,sans-serif;}' +
'.mouse-clock .mc-hand{width:16px;height:16px;font:bold 16px Arial,sans-serif;}';
root.appendChild(css);
function make(chars, cls, color) {
return chars.map(function (c) {
var el = document.createElement('div');
el.className = cls;
el.style.color = color;
el.textContent = c;
root.appendChild(el);
return el;
});
}
var elDate = make(D, 'mc-date', o.dateColor);
var elFace = make(Face, 'mc-face', o.faceColor);
var elH = make(H, 'mc-hand', o.hourColor);
var elM = make(M, 'mc-hand', o.minuteColor);
var elS = make(S, 'mc-hand', o.secondColor);
document.body.appendChild(root);
function place(el, top, left) { el.style.transform = 'translate(' + left + 'px,' + top + 'px)'; }
// Pointer Events 分辨滑鼠和手指(手機點擊後補發的滑鼠事件不會干擾)
function onPointer(e) {
var touch = e.pointerType !== 'mouse';
if (isTouch && !touch) return;
ymouse = e.clientY + (touch ? o.touchOffsetY : o.offsetY);
xmouse = e.clientX + (touch ? o.touchOffsetX : o.offsetX);
}
// 手指滑動捲頁時瀏覽器會中斷 pointermove,改由 touchmove 接手
function onTouch(e) {
var t = e.touches[0];
if (!t) return;
ymouse = t.clientY + o.touchOffsetY;
xmouse = t.clientX + o.touchOffsetX;
}
document.addEventListener('pointerdown', onPointer, { passive: true });
document.addEventListener('pointermove', onPointer, { passive: true });
document.addEventListener('touchmove', onTouch, { passive: true });
function draw() {
var t = new Date(), i;
var sec = -1.57 + Math.PI * t.getSeconds() / 30;
var min = -1.57 + Math.PI * t.getMinutes() / 30;
var hrs = -1.575 + Math.PI * t.getHours() / 6 + Math.PI * t.getMinutes() / 360;
for (i = 0; i < n; i++)
place(elFace[i], y[i] + R * Math.sin(-1.0471 + i * Split * Math.PI / 180),
x[i] + R * Math.cos(-1.0471 + i * Split * Math.PI / 180));
for (i = 0; i < H.length; i++)
place(elH[i], y[i] + HandY + (i * HandLen) * Math.sin(hrs), x[i] + HandX + (i * HandLen) * Math.cos(hrs));
for (i = 0; i < M.length; i++)
place(elM[i], y[i] + HandY + (i * HandLen) * Math.sin(min), x[i] + HandX + (i * HandLen) * Math.cos(min));
for (i = 0; i < S.length; i++)
place(elS[i], y[i] + HandY + (i * HandLen) * Math.sin(sec), x[i] + HandX + (i * HandLen) * Math.cos(sec));
for (i = 0; i < D.length; i++)
place(elDate[i], Dy[i] + R * 1.5 * Math.sin(currStep + i * Dsplit * Math.PI / 180),
Dx[i] + R * 1.5 * Math.cos(currStep + i * Dsplit * Math.PI / 180));
currStep -= o.dateSpeed;
}
function tick() {
if (document.hidden) return; // 分頁在背景時不計算
var i;
Dy[0] = Math.round(DY[0] += (ymouse - DY[0]) * o.speed);
Dx[0] = Math.round(DX[0] += (xmouse - DX[0]) * o.speed);
for (i = 1; i < D.length; i++) {
Dy[i] = Math.round(DY[i] += (Dy[i - 1] - DY[i]) * o.speed);
Dx[i] = Math.round(DX[i] += (Dx[i - 1] - DX[i]) * o.speed);
}
y[0] = Math.round(Y[0] += (ymouse - Y[0]) * o.speed);
x[0] = Math.round(X[0] += (xmouse - X[0]) * o.speed);
for (i = 1; i < n; i++) {
y[i] = Math.round(Y[i] += (y[i - 1] - Y[i]) * o.speed);
x[i] = Math.round(X[i] += (x[i - 1] - X[i]) * o.speed);
}
draw();
}
var timer = setInterval(tick, 20); // 原版每 20ms 一格,保持相同節奏
running = {
stop: function () {
clearInterval(timer);
document.removeEventListener('pointerdown', onPointer);
document.removeEventListener('pointermove', onPointer);
document.removeEventListener('touchmove', onTouch);
if (root.parentNode) root.parentNode.removeChild(root);
running = null;
}
};
return running;
}
// 讀取 <script data-*> 設定,例如 data-hour-color="#c00" data-lang="en"
function fromScriptTag(script) {
var opts = {};
if (!script || !script.dataset) return opts;
for (var k in DEFAULTS) if (script.dataset[k] !== undefined) opts[k] = script.dataset[k];
return opts;
}
var current = document.currentScript;
// 1.1.0:在載入前設定 window.MouseClockOptions = {...} 也可以調整(data-* 屬性優先)
var preset = window.MouseClockOptions;
window.MouseClock = { version: '1.1.0', start: start, stop: function () { if (running) running.stop(); }, defaults: DEFAULTS };
// 加上 data-manual 就不自動啟動,改由 MouseClock.start({...}) 啟動
if (!(current && current.dataset && current.dataset.manual !== undefined)) {
var opts = {}, tagOpts = fromScriptTag(current), key;
if (preset && typeof preset === 'object') for (key in preset) opts[key] = preset[key];
for (key in tagOpts) opts[key] = tagOpts[key];
if (document.body) start(opts);
else document.addEventListener('DOMContentLoaded', function () { start(opts); });
}
})();