Updated StringToHex -> RandomHex

This commit is contained in:
nuttylmao
2025-11-17 23:25:00 +11:00
parent 9d891bc2c9
commit 080c9f6bc8
3 changed files with 33 additions and 12 deletions
+31 -10
View File
@@ -222,21 +222,42 @@ function EscapeRegExp(string) {
} }
// Given a string, return a random hex code. The same input always results in the same output // Given a string, return a random hex code. The same input always results in the same output
function StringToHex(str) { function RandomHex(str) {
// Simple hash function to convert string to a number // Simple hash to convert string to a number
let hash = 0; let hash = 0;
for (let i = 0; i < str.length; i++) { for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash); hash = str.charCodeAt(i) + ((hash << 5) - hash);
hash |= 0; // Convert to 32bit integer hash |= 0;
} }
// Convert hash to a hex color // Use the hash to generate a hue (0360)
let color = '#'; const hue = Math.abs(hash) % 360;
for (let i = 0; i < 3; i++) {
// Extract each byte and convert to 2-digit hex // Force super saturation + readable brightness
const value = (hash >> (i * 8)) & 0xFF; const saturation = 100; // maximum saturation
color += value.toString(16).padStart(2, '0'); const lightness = 55; // tweak 5060 depending on your background
// Convert HSL → RGB → hex
function hslToHex(h, s, l) {
s /= 100;
l /= 100;
const k = n => (n + h / 30) % 12;
const a = s * Math.min(l, 1 - l);
const f = n =>
l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
const r = Math.round(255 * f(0));
const g = Math.round(255 * f(8));
const b = Math.round(255 * f(4));
return (
"#" +
r.toString(16).padStart(2, "0") +
g.toString(16).padStart(2, "0") +
b.toString(16).padStart(2, "0")
);
} }
return color; return hslToHex(hue, saturation, lightness);
} }
+1 -1
View File
@@ -896,7 +896,7 @@ function YouTubeMessage(data) {
if (showUsername) { if (showUsername) {
usernameDiv.innerText = data.user.name; usernameDiv.innerText = data.user.name;
if (randomYouTubeColors) if (randomYouTubeColors)
usernameDiv.style.color = StringToHex(data.user.name); usernameDiv.style.color = RandomHex(data.user.name);
else else
usernameDiv.style.color = youtubeColor; // YouTube users do not have colors, so just set it to red usernameDiv.style.color = youtubeColor; // YouTube users do not have colors, so just set it to red
} }
+1 -1
View File
@@ -1312,7 +1312,7 @@ async function YouTubeMessage(data) {
if (showUsername) { if (showUsername) {
usernameDiv.innerText = data.user.name; usernameDiv.innerText = data.user.name;
if (randomYouTubeColors) if (randomYouTubeColors)
usernameDiv.style.color = StringToHex(data.user.name); usernameDiv.style.color = RandomHex(data.user.name);
else else
usernameDiv.style.color = youtubeColor; // YouTube users do not have colors, so just set it to red usernameDiv.style.color = youtubeColor; // YouTube users do not have colors, so just set it to red
} }