forked from Gabriel-Denys/RandomGradient
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgradients.js
More file actions
114 lines (91 loc) · 2.99 KB
/
gradients.js
File metadata and controls
114 lines (91 loc) · 2.99 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//preload JSON on start
var event = new Event('gradientload');
var file;
var seednum;
var opt;
//random number generator based on seed
Math.seededRandom = function (seed, max, min) {
Math.seed = 0;
for (var i = 0; i < seed.length; i++) {
Math.seed += parseInt(seed.charCodeAt(i));
}
max = max || 1;
min = min || 0;
Math.seed = (Math.seed * 9301 + 49297) % 233280;
var rnd = Math.seed / 233280;
return Math.floor(min + rnd * (max - min));
}
function hexToRgbA(hex, opacity) {
var c;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
c = hex.substring(1).split('');
if (c.length == 3) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = '0x' + c.join('');
return 'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',' + opacity + ')';
}
throw new Error('Bad Hex');
}
var gradients = {
init: function (options = {
opacity: 1,
hex: true,
array: false
}) {
opt = options;
if (options.opacity < 1 && options.opacity > 0) {
opt.hex = false;
} else {
opt.hex = true;
}
return new Promise(function (resolve, reject) {
$.getJSON('gradients.json', function (data) {
file = data;
window.dispatchEvent(event);
}).done(sc => {
resolve("JSON Loaded");
}).fail(fl => {
reject(Error("JSON not loaded"));
})
})
/*
options.hex if true then enables hex output, else rgba
options.opacity , sets opacity and overrides hex to false
options.array , should we output as array object or string?
*/
},
color: function (seed, opacity = opt.opacity) {
if (opacity < 1 && opacity > 0) {
opt.hex = false;
} else {
opt.hex = true;
}
var returnobject;
if (file.length > 0) {
var randompick = Math.seededRandom(seed, file.length)
if (opt.array) {
var returnarray = new Array();
//if the user wants an array
if (!opt.hex) {
file[randompick].colors.forEach(function (entry, index) {
returnarray.push(hexToRgbA(entry, opacity));
});
returnobject = returnarray;
} else {
returnobject = file[randompick].colors;
}
} else {
if (!opt.hex) {
file[randompick].colors.forEach(function (entry, index) {
returnarray.push(hexToRgbA(entry, opacity));
});
returnobject = returnarray.toString();
} else {
returnobject = file[randompick].colors.toString();
}
}
}
return returnobject;
}
}