function halveBrightness(hexColor) { if (hexColor.charAt(0) =="#") { hexColor = hexColor.substr(1); } var color = parseInt(hexColor, 16); /* using the method of https://stackoverflow.com/a/1787193/1115360 */ color = (color & 0xFEFEFE) >> 1; return padLeft("0", 6, color.toString(16)); }
function padLeft(padChar, finalLength, str) { padChar = padChar.charAt(0); var nPads = finalLength - str.length; var padding =""; for(var i=1; i<=nPads; i++) { padding += padChar; } return padding + str; }
/* using the value from the question */ var y ="#1f77b4"; console.log(halveBrightness(y));
/* check it works when bytes are/will become zero */ console.log(halveBrightness("0001FF")); |
輸出:
0f3b5a
00007f
您可能需要在結(jié)果的開頭放置一個"#"或" 0x",這取決于您使用它的目的。
該文章在 2023/4/12 9:28:14 編輯過