-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolor.js
More file actions
80 lines (76 loc) · 2.39 KB
/
color.js
File metadata and controls
80 lines (76 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
function rgbIntsOfHexadecimalColor(hex){
if (hex.indexOf('#') === 0) {
hex = hex.slice(1);
}
// convert 3-digit hex to 6-digits.
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
if (hex.length !== 6) {
throw new Error('Invalid HEX color.' + hex);
}
var r = parseInt(hex.slice(0, 2), 16),
g = parseInt(hex.slice(2, 4), 16),
b = parseInt(hex.slice(4, 6), 16);
return [r, g, b];
}
function invertColor(hex, bw) {
var [r, g, b] = rgbIntsOfHexadecimalColor(hex);
if (bw) {
// http://stackoverflow.com/a/3943023/112731
return (r * 0.299 + g * 0.587 + b * 0.114) > 186
? '#000000'
: '#FFFFFF';
}
// invert color components
r = (255 - r).toString(16);
g = (255 - g).toString(16);
b = (255 - b).toString(16);
// pad each with zeros and return
return "#" + padZero(r) + padZero(g) + padZero(b);
}
function getIntColor(num) {
var moddedNumber = num % 0x1000000; // Only 6 hex digits needed
var flooredNumber = Math.floor(moddedNumber); // Just in case?
return "#" + padZero(moddedNumber.toString(16), 6);
}
function generateDeterministicColor(constantProperties, rngSettings) {
var scale = constantProperties[0];
var seedString = JSON.stringify(constantProperties);
var tempRNG = new RNG(seedString);
// The prng should make different colors based on scale
var randomIterations = rngSettings.minimumIterations +
Math.abs(scale*2-(scale<0 ? 1 : 0));
var randomNumber = 0;
for(var i = 0; i < randomIterations; i++){
randomNumber = (
(tempRNG.nextByte() << 16) |
(tempRNG.nextByte() << 8) |
(tempRNG.nextByte() & 0xFF)
);
}
var color = getIntColor(randomNumber);
return color;
}
function mixColors(colorList) {
var rNumerator = 0;
var rDenominator = 0;
var gNumerator = 0;
var gDenominator = 0;
var bNumerator = 0;
var bDenominator = 0;
for (var i = 0; i < colorList.length; i++) {
var [r, g, b] = rgbIntsOfHexadecimalColor(colorList[i]);
rNumerator += r;
rDenominator += 1;
gNumerator += g;
gDenominator += 1;
bNumerator += b;
bDenominator += 1;
}
return "#" +
padZero(Math.round(rNumerator/rDenominator).toString(16)) +
padZero(Math.round(gNumerator/gDenominator).toString(16)) +
padZero(Math.round(bNumerator/bDenominator).toString(16))
;
}