Created
December 22, 2021 18:13
-
-
Save crossan007/d70aa0b5117000d0f73a54325a510dba to your computer and use it in GitHub Desktop.
Create Color from a String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Renders an idempotent-ly random color hex code based on the input string | |
* @param str | |
* @returns | |
*/ | |
stringToColor(str: string): string { | |
/** | |
* will end up as a 3-byte "char" array | |
*/ | |
var hex: number[] = []; | |
var exciterRanges = [ | |
[32,70], | |
[71,79], | |
[80,95]]; | |
var exciters =[0,0,0]; | |
const MAX_COLOR_BRIGHTNESS = 190; | |
const MIN_COLOR_BRIGHTNESS = 60; | |
const MOD=3; | |
for(var i=0;i<3*str.length;i++) { | |
for(var y=0;y<3;y++) { | |
exciters[y] += (exciterRanges[y][0] < str.toUpperCase().charCodeAt(i%str.length) && | |
exciterRanges[y][1] > str.toUpperCase().charCodeAt(i%str.length) | |
)?1 : 0 | |
} | |
hex[i%MOD] =(Math.trunc((str.charCodeAt(i%MOD) + str.charCodeAt(i%str.length)*exciters[i%MOD])/2) % MAX_COLOR_BRIGHTNESS); | |
if(hex[i%MOD] < MIN_COLOR_BRIGHTNESS) { hex[i%MOD] = MIN_COLOR_BRIGHTNESS } | |
//console.log("hex: @" + i%MOD + "(" + i%MOD + "): " + hex[i%MOD] + " exciter: " + exciters[i%MOD]) | |
} | |
// convert the byte array to a string | |
var retCode:string = '#'; | |
for(var i=0;i<MOD;i++) { | |
retCode += hex[i].toString(16); | |
} | |
console.log("color " + retCode + " from: " + str) | |
return retCode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment