function hexToRgb(hex) {
    let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

function rgbToHex(r, g, b) {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

function mixColors(color1, color2, ratio) {
    let rgb1 = hexToRgb(color1);
    let rgb2 = hexToRgb(color2);

    let r = Math.round(rgb1.r * ratio + rgb2.r * (1 - ratio));
    let g = Math.round(rgb1.g * ratio + rgb2.g * (1 - ratio));
    let b = Math.round(rgb1.b * ratio + rgb2.b * (1 - ratio));

    return rgbToHex(r, g, b);
}
let colors = ["#191970", "#ADD8E6", "#87CEEB", "#1E90FF", "#0000FF", "#00008B", "#000080"];
let times = [2, 7, 9, 11, 13, 16, 20]; // 將時間段調整為每4小時一次
function updateColor(hour, minute, second) {
    let date = new Date();
    if (hour !== undefined) { date.setHours(hour); }
    if (minute !== undefined) { date.setMinutes(minute); }
    if (second !== undefined) { date.setSeconds(second); }

    hour = date.getHours();
    minute = date.getMinutes();
    let i;
    for (i = 0; i < times.length - 1; i++) {
        if (hour < times[i + 1]) {
            break;
        }
    }
    let adjustedTime =times[i];
    var adjustedhour =hour
    if (hour < times[0]) {
        adjustedTime=times[times.length-1];
        adjustedhour+=24
    }

var time1To2
if (adjustedhour>23){

    time1To2=24+times[0]-adjustedTime
}else{

    time1To2=Math.abs(times[(i + 1)%times.length]-times[i])
}
console.log((adjustedhour + (minute / 60)) - adjustedTime)
    let passedRatio = ((adjustedhour + (minute / 60)) - adjustedTime ) / time1To2;

    let color1 = colors[i];
    let color2 = colors[(i + 1) % colors.length];
    let color = mixColors(color1, color2, 1-passedRatio);

    //console.log(`passedRatio:${passedRatio},\r\n now: ${date.toLocaleTimeString()}`)
    document.body.style.backgroundColor = color;
    //debugger
}

var count = 0;
var minute = 0;
updateColor(count, minute, 0); //將 count 作為小時,minute 作為分鐘傳入
setInterval(function() {
    minute = (minute + 15) % 60;
    if (minute === 0) { //每過一小時,小時數增加一個單位
        count = (count + 1) % 24;
    }
    updateColor(count, minute, 0); //每次更新時,將 count 作為小時,minute 作為分鐘傳入
}, 100); //更新顏色

直接把程式码贴到网址about:blank的控制台

按讚的人:

共有 4 則留言

运行程式开始灌水

setInterval(()=> { fetch("https://codelove.tw/@yydsAwA/post/2andkx")},100)
按讚的人:

不流暢嗎?FPS 不夠而已吧?

把最後一行改成 33 如何?

}, 33); //更新顏色

我剛看滿流暢的,你試試看吧

本來是要用一天的變化的(但是0:15那邊好像顏色不是很正確)

誰家半夜天還那麼亮

按讚的人: