Color Spectrum Optimization - javascript

I have the following implementation, it works and functional. I am checking if fname properties are same in the following javascript object, then I assign the same color for these paired objects.
Here is one javascript object sample:
{"value": 10,"series": 1,"category": "LG","fname": "","valueColor": ""},
However, I would like to use more distinguished colors, rather than very similar color, for example in the given fiddle, colors are almost all in green spectrum. Also I do not want to give any color value where value property equals to 0
Here is the core implementation
function colorSpectrum(N) {
var colorMap = [], inc = 50, start = 1000;
for (i = start; i < start+N*inc; i+=inc) {
var num = ((4095 * i) >>> 0).toString(16);
while (num.length < 3) {
num = "0" + num;
}
colorMap.push("#" + num);
}
return colorMap;
}
function process(data){
var map = {}, colorMap = colorSpectrum(data.length);
data.forEach(function(item, index){
if(!map.hasOwnProperty(item.fname)){
map[item.fname] = colorMap[index];
}
data[index].valueColor = map[item.fname];
});
return data;
}
FIDDLE

Try picking random colors
function colorSpectrum(N) {
var colorMap = [];
for (i = 0; i < N; i+=1) {
var color = getRndColor()
colorMap.push("#"+color);
}
return colorMap;
}
function getRndColor() {
var n = Math.floor(Math.random()*255*255*255);
var hex = Number(n).toString(16);
while(hex.length < 6) {
hex = "0"+hex;
}
return hex;
}

If you want a full range of colors from black to white, you need to change this part:
var colorMap = [], inc = 50, start = 1000;
for (i = start; i < start+N*inc; i+=inc) {
You see, the loop starts from 1000, which is the color #3e8, already green. The scale should go from 0 to 4095 (for 3-character values like #007, #abc, etc...), with having the increment based on the amount of data.
However, I'd suggest getting at least a little bit of the control by having all RGB components generated separately instead of the full HEX value right away.

Related

How do I check if 2 numbers are the same from Math.random [duplicate]

Can't seem to find an answer to this, say I have this:
setInterval(function() {
m = Math.floor(Math.random()*7);
$('.foo:nth-of-type('+m+')').fadeIn(300);
}, 300);
How do I make it so that random number doesn't repeat itself. For example if the random number is 2, I don't want 2 to come out again.
There are a number of ways you could achieve this.
Solution A:
If the range of numbers isn't large (let's say less than 10), you could just keep track of the numbers you've already generated. Then if you generate a duplicate, discard it and generate another number.
Solution B:
Pre-generate the random numbers, store them into an array and then go through the array. You could accomplish this by taking the numbers 1,2,...,n and then shuffle them.
shuffle = function(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var randorder = shuffle([0,1,2,3,4,5,6]);
var index = 0;
setInterval(function() {
$('.foo:nth-of-type('+(randorder[index++])+')').fadeIn(300);
}, 300);
Solution C:
Keep track of the numbers available in an array. Randomly pick a number. Remove number from said array.
var randnums = [0,1,2,3,4,5,6];
setInterval(function() {
var m = Math.floor(Math.random()*randnums.length);
$('.foo:nth-of-type('+(randnums[m])+')').fadeIn(300);
randnums = randnums.splice(m,1);
}, 300);
You seem to want a non-repeating random number from 0 to 6, so similar to tskuzzy's answer:
var getRand = (function() {
var nums = [0,1,2,3,4,5,6];
var current = [];
function rand(n) {
return (Math.random() * n)|0;
}
return function() {
if (!current.length) current = nums.slice();
return current.splice(rand(current.length), 1);
}
}());
It will return the numbers 0 to 6 in random order. When each has been drawn once, it will start again.
could you try that,
setInterval(function() {
m = Math.floor(Math.random()*7);
$('.foo:nth-of-type(' + m + ')').fadeIn(300);
}, 300);
I like Neal's answer although this is begging for some recursion. Here it is in java, you'll still get the general idea. Note that you'll hit an infinite loop if you pull out more numbers than MAX, I could have fixed that but left it as is for clarity.
edit: saw neal added a while loop so that works great.
public class RandCheck {
private List<Integer> numbers;
private Random rand;
private int MAX = 100;
public RandCheck(){
numbers = new ArrayList<Integer>();
rand = new Random();
}
public int getRandomNum(){
return getRandomNumRecursive(getRand());
}
private int getRandomNumRecursive(int num){
if(numbers.contains(num)){
return getRandomNumRecursive(getRand());
} else {
return num;
}
}
private int getRand(){
return rand.nextInt(MAX);
}
public static void main(String[] args){
RandCheck randCheck = new RandCheck();
for(int i = 0; i < 100; i++){
System.out.println(randCheck.getRandomNum());
}
}
}
Generally my approach is to make an array containing all of the possible values and to:
Pick a random number <= the size of the array
Remove the chosen element from the array
Repeat steps 1-2 until the array is empty
The resulting set of numbers will contain all of your indices without repetition.
Even better, maybe something like this:
var numArray = [0,1,2,3,4,5,6];
numArray.shuffle();
Then just go through the items because shuffle will have randomized them and pop them off one at a time.
Here's a simple fix, if a little rudimentary:
if(nextNum == lastNum){
if (nextNum == 0){nextNum = 7;}
else {nextNum = nextNum-1;}
}
If the next number is the same as the last simply minus 1 unless the number is 0 (zero) and set it to any other number within your set (I chose 7, the highest index).
I used this method within the cycle function because the only stipulation on selecting a number was that is musn't be the same as the last one.
Not the most elegant or technically gifted solution, but it works :)
Use sets. They were introduced to the specification in ES6. A set is a data structure that represents a collection of unique values, so it cannot include any duplicate values. I needed 6 random, non-repeatable numbers ranging from 1-49. I started with creating a longer set with around 30 digits (if the values repeat the set will have less elements), converted the set to array and then sliced it's first 6 elements. Easy peasy. Set.length is by default undefined and it's useless that's why it's easier to convert it to an array if you need specific length.
let randomSet = new Set();
for (let index = 0; index < 30; index++) {
randomSet.add(Math.floor(Math.random() * 49) + 1)
};
let randomSetToArray = Array.from(randomSet).slice(0,6);
console.log(randomSet);
console.log(randomSetToArray);
An easy way to generate a list of different numbers, no matter the size or number:
function randomNumber(max) {
return Math.floor(Math.random() * max + 1);
}
const list = []
while(list.length < 10 ){
let nbr = randomNumber(500)
if(!list.find(el => el === nbr)) list.push(nbr)
}
console.log("list",list)
I would like to add--
var RecordKeeper = {};
SRandom = function () {
currTimeStamp = new Date().getTime();
if (RecordKeeper.hasOwnProperty(currTimeStamp)) {
RecordKeeper[currTimeStamp] = RecordKeeper[currTimeStamp] + 1;
return currTimeStamp.toString() + RecordKeeper[currTimeStamp];
}
else {
RecordKeeper[currTimeStamp] = 1;
return currTimeStamp.toString() + RecordKeeper[currTimeStamp];
}
}
This uses timestamp (every millisecond) to always generate a unique number.
you can do this. Have a public array of keys that you have used and check against them with this function:
function in_array(needle, haystack)
{
for(var key in haystack)
{
if(needle === haystack[key])
{
return true;
}
}
return false;
}
(function from: javascript function inArray)
So what you can do is:
var done = [];
setInterval(function() {
var m = null;
while(m == null || in_array(m, done)){
m = Math.floor(Math.random()*7);
}
done.push(m);
$('.foo:nth-of-type('+m+')').fadeIn(300);
}, 300);
This code will get stuck after getting all seven numbers so you need to make sure it exists after it fins them all.

How to reduce number of computations during d3.js transition?

So right now, I'm trying to implement a search bar function into my d3.js plot. Right now it doesn't do anything, but that's not the issue at the moment. The problem is that when I type/delete something from the bar, there's visible lag/choppiness in the characters appearing/disappearing. I believe the issue is stemming from my plot. I have 140+ dots moving around the screen, and their position is being interpolated. So from the beginning to the end of the transition, my code has to compute 140 positions thousands of times over.
I've looked into trying to reduce the cardinality of the d3.interpolateNumber function, but it appears that there isn't a third argument to change the number of terms like in a linspace command. Right now I have an array of 1000 numbers for my function to run through, but I don't know how to pass the array to my other functions.
Below are the pertinent functions for this issue. The commented line in tweenPatch is the original code I had that made my code run, but gave my plot computational issues. Variables arr, curr, and step were my attempt to fix the situation, but I haven't been able to figure out how to pass the array into displayPatch().
function tweenPatch() {
var patch = d3.interpolateNumber(1, 26);
var arr = [];
var curr = 1;
var step = (26 - 1) / (1000 - 1);
for (var i = 0; i < 1000; i++) {
arr.push(curr + (step * i));
}
return arr.forEach(function(d) {
console.log(arr[d]);
displayPatch(arr[d]);
});
//return function(t) { displayPatch(t); };
}
function displayPatch(patch) {
dots.data(interpolateData(patch), function(d) { return d.name; }).call(position).sort(order);
var inter = Math.floor(patch);
var seas = 8;
var patc = 1;
if (inter > 24) {
seas = 9;
patc = inter - 24;
} else {
patc = inter;
}
label.text("Patch " + seas + "." + patc);
}
function interpolateValues(values, number) {
old = Math.floor(number);
upd = Math.ceil(number);
var old_data = values.filter(function(d) {return d.internal == old;});
var new_data = values.filter(function(d) {return d.internal == upd;});
var oobj = old_data[0];
var nobj = new_data[0];
var onum = oobj[Object.keys(oobj)[4]];
var nnum = nobj[Object.keys(nobj)[4]];
var difint = number - old;
var difdis = 0;
var newnum = nnum;
if (nnum > onum) {
difdis = nnum - onum;
newnum = ((difint) * difdis) + onum;
} else if (onum > nnum) {
difdis = onum - nnum;
newnum = onum - ((difint) * difdis);
}
return newnum;
}
I believe switching my SVG to a canvas may help things, but since I have no knowledge of canvas I'd rather leave that as a last resort.

Getting new colors randomly with loop

I am trying to randomize colors by generating random number, then applying
it to array to get an color array containing font-color and background-color.
At every "skill" I want to have unique color scheme. So each time I loop skill array I loop color array to fetch color scheme. If this color scheme number (which is same as the randomNumber) is already in use I random again. I do this with do/while loop. When color is not found it pushes it to usedColors array and paints the picture.
For some reason I am still getting same colors. I pasted two pictures to the bottom. Console.log image is about usedColors array (the randomly generated numbers)
var usedColors = [];
$.each(knowledges, (i, knowledge) => {
do {
var r = Math.floor(Math.random() * Math.floor(colors.length)),
rColors = colors[r];
} while ($.inArray(r, usedColors) == 0);
usedColors.push(r);
$("#knowledges div").append(
$("<p />").addClass("knowledge").text(knowledge).css({"background-color": rColors[0], "color": rColors[1]})
);
});
inArray gives position of the matching element. So compare against -1, to know that element is not present in the usedColors array.
var usedColors = [];
$.each(knowledges, (i, knowledge) => {
do {
var r = Math.floor(Math.random() * Math.floor(colors.length)),
rColors = colors[r];
} while ($.inArray(r, usedColors) != -1);
usedColors.push(r);
$("#knowledges div").append(
$("<p />").addClass("knowledge").text(knowledge).css({"background-color": rColors[0], "color": rColors[1]})
);
});
To generate array of unique numbers from certain interval you can do this.
In your case the range will be 0, arr.length - 1.
// function that will generate random unique random numbers between start
// and end, and store already generated numbers in closure
function generateUniqueRandom(start, end) {
const used = [];
function generateInner() {
let r;
while (!r) {
r = Math.floor(Math.random() * (end - start) + 1) + start;
if (used.includes(r)) {
r = null;
} else {
used.push(r);
}
}
return r;
}
return generateInner;
}
const random1 = generateUniqueRandom(0, 20);
const nums1 = [];
for (let i = 0; i < 10; i++) {
nums1.push(random1());
}
console.log(nums1);
const random2 = generateUniqueRandom(0, 20);
const nums2 = [];
for (let i = 0; i < 20; i++) {
nums2.push(random2());
}
console.log(nums2);
But you need to be careful not to generate more numbers that the specified range is, otherwise you will be stuck in an infinite loop.
In your while loop, are you checking if the array is unique? If so, it looks like you may not be using $.inArray correctly.
Put this in your while loop:$.inArray(r, usedColors) !== -1
jQuery.inArray(), how to use it right?
I think your loop method has many interactions, I mean your loop is traveling so much that it only ends until you find the random number that is not in the array (A short performance problem). An alternative method so that the array elements are random:
function shuffleArray(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const colors = [["black","green"], ["white","blue"], ["pink","white"]];
let usedColors = shuffleArray(colors);
//You can now do this:
$.each(knowledges, (i, knowledge) => {
$("#knowledges div").append(
$("<p />").addClass("knowledge").text(knowledge).css({"background-color": usedColors[i][0], "color": usedColors[i][1]})
);
});

Change the color of objects with extendscript

I've had a look around and can't find anything to do this, so I think I'm probably asking the wrong question.
I have a series of objects on a page in illustrator with a specific colour in RGB, say its 255 red. I want to select items with this color or loop through to see if an item is this color and change it to a CMYK colour, say 75% grey
It done this but it always selects the item to change it
var currPageItem=app.activeDocument.activeLayer;
var myColour = new RGBColor("255,0,0")//initial default colour
var myGrey= new CMYKColor("0,0,0,75")//initial default grey
// Stepping through each item on the layer.
for (var i = 0; i < currPageItem.pageItems.length; i++) {
var currentItem = currPageItem.pageItems[i];
//$.writeln("Object name=", currentItem);
if (currentItem.RGBColor=myColour) {
$.writeln("Colour function",i);
};
}
I'd like to be able to change stroke colours also. Any help really appreciated, very stuck on this
Thanks for putting me in the correct direction Josh. I think I've now got it. Firstly the document color mode under the file menu has to be set to RGB. If this isn't done then as it script reads through the page items it checks them as CMYK and so doesn't recogniise any RGB values.
Also it check the values to a gazillion decimal places so these need rounding. Have made the following adjustments and this seems to work. Any other improvement most welcome
var layer = app.activeDocument.activeLayer;
var testColor = new RGBColor()//initial default colour
testColor.red = 180;
testColor.green = 93;
testColor.blue = 120;
var myGrey= new CMYKColor()//initial default grey
myGrey.black=75;
// Stepping through each item on the layer.
for (var i = 0; i < layer.pathItems.length; i++) {
var item = layer.pathItems[i];
$.writeln("Test colour ",Math.round( item.fillColor.red))
if (Math.round(item.fillColor.red) == testColor.red &&
Math.round(item.fillColor.green)== testColor.green &&
Math.round(item.fillColor.blue) == testColor.blue)
{
$.writeln("Color function",i );
item.fillColor = myGrey;
}
}
Using something similar for pre-press work.
I adapted the RGB version above convert all rich black to K only. Still experimenting with color values and will add a way to also check the stroke color.
Thank you! Was searching for a solution for a long time.
var layer = app.activeDocument.activeLayer;
var testColor = new CMYKColor(); //initial default colour
testColor.cyan = 62;
testColor.magenta = 62;
testColor.yellow = 62;
testColor.black = 62;
var myGrey = new CMYKColor(); //initial default grey
myGrey.black = 100;
// Stepping through each item on the layer.
for (var i = 0; i < layer.pathItems.length; i++) {
var item = layer.pathItems[i];
$.writeln("Test colour ", Math.round(item.fillColor.cyan));
if (Math.round(item.fillColor.cyan) > testColor.red &&
Math.round(item.fillColor.magenta) > testColor.magenta &&
Math.round(item.fillColor.yellow) > testColor.yellow &&
Math.round(item.fillColor.black) > testColor.black) {
$.writeln("Color function", i);
item.fillColor = myGrey;
item.selected = true;
}
}
This should give you a good start with what you're trying to accomplish. *There is probably a better way to code this, but the illustrator documentation doesn't seem to be too helpful in figuring out how to instantiate or compare colors.
var layer = app.activeDocument.activeLayer;
var testColor = new RGBColor(); // initial default colour
testColor.red = 255; // rest of the values default to 0
var greyColor = new CMYKColor(); // initial default grey
greyColor.black = 75; // rest of the values default to 0
for (var i=0; i<layer.pathItems.length; i++) {
var item = layer.pathItems[i];
if (item.fillColor.red === testColor.red &&
item.fillColor.blue === testColor.blue &&
item.fillColor.green === testColor.green)
{
item.fillColor = greyColor;
}
}

Create a hexadecimal colour based on a string with JavaScript

I want to create a function that will accept any old string (will usually be a single word) and from that somehow generate a hexadecimal value between #000000 and #FFFFFF, so I can use it as a colour for a HTML element.
Maybe even a shorthand hex value (e.g: #FFF) if that's less complicated. In fact, a colour from a 'web-safe' palette would be ideal.
Here's an adaptation of CD Sanchez' answer that consistently returns a 6-digit colour code:
var stringToColour = function(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xFF;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
}
Usage:
stringToColour("greenish");
// -> #9bc63b
Example:
http://jsfiddle.net/sUK45/
(An alternative/simpler solution might involve returning an 'rgb(...)'-style colour code.)
Just porting over the Java from Compute hex color code for an arbitrary string to Javascript:
function hashCode(str) { // java String#hashCode
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function intToRGB(i){
var c = (i & 0x00FFFFFF)
.toString(16)
.toUpperCase();
return "00000".substring(0, 6 - c.length) + c;
}
To convert you would do:
intToRGB(hashCode(your_string))
I wanted similar richness in colors for HTML elements, I was surprised to find that CSS now supports hsl() colors, so a full solution for me is below:
Also see How to automatically generate N "distinct" colors? for more alternatives more similar to this.
Edit: updating based on #zei's version (with american spelling)
var stringToColor = (string, saturation = 100, lightness = 75) => {
let hash = 0;
for (let i = 0; i < string.length; i++) {
hash = string.charCodeAt(i) + ((hash << 5) - hash);
hash = hash & hash;
}
return `hsl(${(hash % 360)}, ${saturation}%, ${lightness}%)`;
}
// For the sample on stackoverflow
function colorByHashCode(value) {
return "<span style='color:" + stringToColor(value) + "'>" + value + "</span>";
}
document.body.innerHTML = [
"javascript",
"is",
"nice",
].map(colorByHashCode).join("<br/>");
span {
font-size: 50px;
font-weight: 800;
}
In HSL its Hue, Saturation, Lightness. So the hue between 0-359 will get all colors, saturation is how rich you want the color, 100% works for me. And Lightness determines the deepness, 50% is normal, 25% is dark colors, 75% is pastel. I have 30% because it fit with my color scheme best.
Here is my 2021 version with Reduce Function and HSL Color.
function getBackgroundColor(stringInput) {
let stringUniqueHash = [...stringInput].reduce((acc, char) => {
return char.charCodeAt(0) + ((acc << 5) - acc);
}, 0);
return `hsl(${stringUniqueHash % 360}, 95%, 35%)`;
}
Using the hashCode as in Cristian Sanchez's answer with hsl and modern javascript, you can create a color picker with good contrast like this:
function hashCode(str) {
let hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function pickColor(str) {
return `hsl(${hashCode(str) % 360}, 100%, 80%)`;
}
one.style.backgroundColor = pickColor(one.innerText)
two.style.backgroundColor = pickColor(two.innerText)
div {
padding: 10px;
}
<div id="one">One</div>
<div id="two">Two</div>
Since it's hsl, you can scale luminance to get the contrast you're looking for.
function hashCode(str) {
let hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function pickColor(str) {
// Note the last value here is now 50% instead of 80%
return `hsl(${hashCode(str) % 360}, 100%, 50%)`;
}
one.style.backgroundColor = pickColor(one.innerText)
two.style.backgroundColor = pickColor(two.innerText)
div {
color: white;
padding: 10px;
}
<div id="one">One</div>
<div id="two">Two</div>
I find that generating random colors tends to create colors that do not have enough contrast for my taste. The easiest way I have found to get around that is to pre-populate a list of very different colors. For every new string, assign the next color in the list:
// Takes any string and converts it into a #RRGGBB color.
var StringToColor = (function(){
var instance = null;
return {
next: function stringToColor(str) {
if(instance === null) {
instance = {};
instance.stringToColorHash = {};
instance.nextVeryDifferntColorIdx = 0;
instance.veryDifferentColors = ["#000000","#00FF00","#0000FF","#FF0000","#01FFFE","#FFA6FE","#FFDB66","#006401","#010067","#95003A","#007DB5","#FF00F6","#FFEEE8","#774D00","#90FB92","#0076FF","#D5FF00","#FF937E","#6A826C","#FF029D","#FE8900","#7A4782","#7E2DD2","#85A900","#FF0056","#A42400","#00AE7E","#683D3B","#BDC6FF","#263400","#BDD393","#00B917","#9E008E","#001544","#C28C9F","#FF74A3","#01D0FF","#004754","#E56FFE","#788231","#0E4CA1","#91D0CB","#BE9970","#968AE8","#BB8800","#43002C","#DEFF74","#00FFC6","#FFE502","#620E00","#008F9C","#98FF52","#7544B1","#B500FF","#00FF78","#FF6E41","#005F39","#6B6882","#5FAD4E","#A75740","#A5FFD2","#FFB167","#009BFF","#E85EBE"];
}
if(!instance.stringToColorHash[str])
instance.stringToColorHash[str] = instance.veryDifferentColors[instance.nextVeryDifferntColorIdx++];
return instance.stringToColorHash[str];
}
}
})();
// Get a new color for each string
StringToColor.next("get first color");
StringToColor.next("get second color");
// Will return the same color as the first time
StringToColor.next("get first color");
While this has a limit to only 64 colors, I find most humans can't really tell the difference after that anyway. I suppose you could always add more colors.
While this code uses hard-coded colors, you are at least guaranteed to know during development exactly how much contrast you will see between colors in production.
Color list has been lifted from this SO answer, there are other lists with more colors.
If your inputs are not different enough for a simple hash to use the entire color spectrum, you can use a seeded random number generator instead of a hash function.
I'm using the color coder from Joe Freeman's answer, and David Bau's seeded random number generator.
function stringToColour(str) {
Math.seedrandom(str);
var rand = Math.random() * Math.pow(255,3);
Math.seedrandom(); // don't leave a non-random seed in the generator
for (var i = 0, colour = "#"; i < 3; colour += ("00" + ((rand >> i++ * 8) & 0xFF).toString(16)).slice(-2));
return colour;
}
I have opened a pull request to Please.js that allows generating a color from a hash.
You can map the string to a color like so:
const color = Please.make_color({
from_hash: "any string goes here"
});
For example, "any string goes here" will return as "#47291b"
and "another!" returns as "#1f0c3d"
Javascript Solution inspired by Aslam's solution but returns a color in hex color code
/**
*
* #param {String} - stringInput - 'xyz'
* #returns {String} - color in hex color code - '#ae6204'
*/
function getBackgroundColor(stringInput) {
const h = [...stringInput].reduce((acc, char) => {
return char.charCodeAt(0) + ((acc << 5) - acc);
}, 0);
const s = 95, l = 35 / 100;
const a = s * Math.min(l, 1 - l) / 100;
const f = n => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color).toString(16).padStart(2, '0'); // convert to Hex and prefix "0" if needed
};
return `#${f(0)}${f(8)}${f(4)}`;
}
Yet another solution for random colors:
function colorize(str) {
for (var i = 0, hash = 0; i < str.length; hash = str.charCodeAt(i++) + ((hash << 5) - hash));
color = Math.floor(Math.abs((Math.sin(hash) * 10000) % 1 * 16777216)).toString(16);
return '#' + Array(6 - color.length + 1).join('0') + color;
}
It's a mixed of things that does the job for me.
I used JFreeman Hash function (also an answer in this thread) and Asykäri pseudo random function from here and some padding and math from myself.
I doubt the function produces evenly distributed colors, though it looks nice and does that what it should do.
Here's a solution I came up with to generate aesthetically pleasing pastel colours based on an input string. It uses the first two chars of the string as a random seed, then generates R/G/B based on that seed.
It could be easily extended so that the seed is the XOR of all chars in the string, rather than just the first two.
Inspired by David Crow's answer here: Algorithm to randomly generate an aesthetically-pleasing color palette
//magic to convert strings to a nice pastel colour based on first two chars
//
// every string with the same first two chars will generate the same pastel colour
function pastel_colour(input_str) {
//TODO: adjust base colour values below based on theme
var baseRed = 128;
var baseGreen = 128;
var baseBlue = 128;
//lazy seeded random hack to get values from 0 - 256
//for seed just take bitwise XOR of first two chars
var seed = input_str.charCodeAt(0) ^ input_str.charCodeAt(1);
var rand_1 = Math.abs((Math.sin(seed++) * 10000)) % 256;
var rand_2 = Math.abs((Math.sin(seed++) * 10000)) % 256;
var rand_3 = Math.abs((Math.sin(seed++) * 10000)) % 256;
//build colour
var red = Math.round((rand_1 + baseRed) / 2);
var green = Math.round((rand_2 + baseGreen) / 2);
var blue = Math.round((rand_3 + baseBlue) / 2);
return { red: red, green: green, blue: blue };
}
GIST is here: https://gist.github.com/ro-sharp/49fd46a071a267d9e5dd
Here is another try:
function stringToColor(str){
var hash = 0;
for(var i=0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 3) - hash);
}
var color = Math.abs(hash).toString(16).substring(0, 6);
return "#" + '000000'.substring(0, 6 - color.length) + color;
}
All you really need is a good hash function. On node, I just use
const crypto = require('crypto');
function strToColor(str) {
return '#' + crypto.createHash('md5').update(str).digest('hex').substr(0, 6);
}
After having a look at the rather code intensive and rather old answers, I thought I'd review this issue from a 2021 standpoint just for fun, hope it is of use to anyone. Having the HSL color model and the crypto API implemented in pretty much all browsers (except IE of course) today, it could be solved as simple as that:
async function getColor(text, minLightness = 40, maxLightness = 80, minSaturation = 30, maxSaturation = 100) {
let hash = await window.crypto.subtle.digest("SHA-1", new TextEncoder().encode(text));
hash = new Uint8Array(hash).join("").slice(16);
return "hsl(" + (hash % 360) + ", " + (hash % (maxSaturation - minSaturation) + minSaturation) + "%, " + (hash % (maxLightness - minLightness) + minLightness) + "%)";
}
function generateColor() {
getColor(document.getElementById("text-input").value).then(color => document.querySelector(".swatch").style.backgroundColor = color);
}
input {
padding: 5px;
}
.swatch {
margin-left: 10px;
width: 28px;
height: 28px;
background-color: white;
border: 1px solid gray;
}
.flex {
display: flex;
}
<html>
<body>
<div class="flex">
<form>
<input id="text-input" type="text" onInput="generateColor()" placeholder="Type here"></input>
</form>
<div class="swatch"></div>
</div>
</body>
</html>
This should be way faster than generating hashes manually, and also offers a way to define saturation and lightness in case you don't want colors that are too flat or too bright or too dark (e.g. if you want to write text on those colors).
2023 version plain and simple TypeScript arrow function that returns HSL color.
const stringToColor = (value: string) => {
let hash = 0;
for (let i = 0; i < value.length; i++) {
hash = value.charCodeAt(i) + ((hash << 5) - hash);
}
return `hsl(${hash % 360}, 85%, 35%)`;
};
This function does the trick. It's an adaptation of this, fairly longer implementation this repo ..
const color = (str) => {
let rgb = [];
// Changing non-hexadecimal characters to 0
str = [...str].map(c => (/[0-9A-Fa-f]/g.test(c)) ? c : 0).join('');
// Padding string with zeroes until it adds up to 3
while (str.length % 3) str += '0';
// Dividing string into 3 equally large arrays
for (i = 0; i < str.length; i += str.length / 3)
rgb.push(str.slice(i, i + str.length / 3));
// Formatting a hex color from the first two letters of each portion
return `#${rgb.map(string => string.slice(0, 2)).join('')}`;
}
I have a situation where i want to display a background based on the username of the user and display the username's first letter on top.
i used the belove code for that it worked well for me
var stringToColour = function (str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xff;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;}
To find the appropriate colour you can use
function lightOrDark(color) {
// Check the format of the color, HEX or RGB?
if (color.match(/^rgb/)) {
// If HEX --> store the red, green, blue values in separate variables
color = color.match(
/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/,
);
var r = color[1];
var g = color[2];
var b = color[3];
} else {
// If RGB --> Convert it to HEX: http://gist.github.com/983661
color = +(
'0x' + color.slice(1).replace(color.length < 5 && /./g, '$&$&')
);
r = color >> 16;
g = (color >> 8) & 255;
b = color & 255;
}
// HSP equation from http://alienryderflex.com/hsp.html
var hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b));
// Using the HSP value, determine whether the color is light or dark
if (hsp > 127.5) {
return 'light';
} else {
return 'dark';
}
}
my code is for Java.
Thanks for all.
public static int getColorFromText(String text)
{
if(text == null || text.length() < 1)
return Color.BLACK;
int hash = 0;
for (int i = 0; i < text.length(); i++)
{
hash = text.charAt(i) + ((hash << 5) - hash);
}
int c = (hash & 0x00FFFFFF);
c = c - 16777216;
return c;
}
I convert this in one line for Python
import hashlib
hash = hashlib.sha1(b'user#email.com').hexdigest()
print("#" + hash[0:6])

Categories

Resources