0
# Utility Functions
1
2
Additional utility functions for color comparison, mixing, random color generation, and working with ratio-based values. These static methods provide essential tools for advanced color operations and programmatic color generation.
3
4
## Capabilities
5
6
### Color Comparison
7
8
#### Compare Colors for Equality
9
10
Compares two colors to determine if they represent the same color value.
11
12
```javascript { .api }
13
/**
14
* Compares two colors for equality
15
* @param color1 - First color (any valid tinycolor input)
16
* @param color2 - Second color (any valid tinycolor input)
17
* @returns boolean indicating if colors are equal
18
*/
19
tinycolor.equals(color1: any, color2: any): boolean;
20
```
21
22
**Usage Examples:**
23
24
```javascript
25
import tinycolor from "tinycolor2";
26
27
// Compare different representations of the same color
28
const red1 = "#ff0000";
29
const red2 = "rgb(255, 0, 0)";
30
const red3 = "red";
31
const red4 = {r: 255, g: 0, b: 0};
32
33
console.log(tinycolor.equals(red1, red2)); // true
34
console.log(tinycolor.equals(red2, red3)); // true
35
console.log(tinycolor.equals(red3, red4)); // true
36
37
// Compare different colors
38
console.log(tinycolor.equals("red", "blue")); // false
39
40
// Compare with slight variations
41
const almostRed = "#ff0001";
42
console.log(tinycolor.equals("red", almostRed)); // false
43
44
// Useful for color validation in arrays
45
const palette = ["#ff0000", "#00ff00", "#0000ff"];
46
const targetColor = "rgb(255, 0, 0)";
47
48
const exists = palette.some(color => tinycolor.equals(color, targetColor));
49
console.log("Color exists in palette:", exists); // true
50
51
// Remove duplicates from color array
52
function removeDuplicateColors(colors) {
53
const unique = [];
54
colors.forEach(color => {
55
const isDuplicate = unique.some(existing => tinycolor.equals(existing, color));
56
if (!isDuplicate) {
57
unique.push(color);
58
}
59
});
60
return unique;
61
}
62
63
const colorsWithDupes = ["red", "#ff0000", "rgb(255,0,0)", "blue", "#0000ff"];
64
const uniqueColors = removeDuplicateColors(colorsWithDupes);
65
```
66
67
### Color Mixing
68
69
#### Mix Two Colors
70
71
Blends two colors together by a specified percentage.
72
73
```javascript { .api }
74
/**
75
* Mixes two colors together
76
* @param color1 - First color (any valid tinycolor input)
77
* @param color2 - Second color (any valid tinycolor input)
78
* @param amount - Mixing percentage (0-100), where 0 returns color1, 100 returns color2
79
* @returns new tinycolor instance representing the mixed color
80
*/
81
tinycolor.mix(color1: any, color2: any, amount?: number): tinycolor;
82
```
83
84
**Usage Examples:**
85
86
```javascript
87
// Basic color mixing
88
const red = "red";
89
const blue = "blue";
90
91
const purple25 = tinycolor.mix(red, blue, 25); // 25% blue, 75% red
92
const purple50 = tinycolor.mix(red, blue, 50); // Equal mix
93
const purple75 = tinycolor.mix(red, blue, 75); // 75% blue, 25% red
94
95
console.log("25% blue:", purple25.toHexString()); // More red
96
console.log("50% mix:", purple50.toHexString()); // Equal purple
97
console.log("75% blue:", purple75.toHexString()); // More blue
98
99
// Create gradients
100
function createGradient(startColor, endColor, steps = 10) {
101
const gradient = [];
102
for (let i = 0; i <= steps; i++) {
103
const amount = (i / steps) * 100;
104
const mixed = tinycolor.mix(startColor, endColor, amount);
105
gradient.push(mixed.toHexString());
106
}
107
return gradient;
108
}
109
110
const redToBlue = createGradient("#ff0000", "#0000ff", 5);
111
console.log("Gradient:", redToBlue);
112
113
// Mix with transparency
114
const opaqueRed = "rgba(255, 0, 0, 1)";
115
const transparentBlue = "rgba(0, 0, 255, 0.3)";
116
const mixed = tinycolor.mix(opaqueRed, transparentBlue, 50);
117
118
console.log("Mixed with alpha:", mixed.toRgbString());
119
120
// Color blending for design
121
function blendColors(baseColor, overlayColor, opacity) {
122
return tinycolor.mix(baseColor, overlayColor, opacity * 100);
123
}
124
125
const background = "#ffffff";
126
const overlay = "#ff0000";
127
const blended = blendColors(background, overlay, 0.3);
128
```
129
130
### Random Color Generation
131
132
#### Generate Random Color
133
134
Creates a completely random color.
135
136
```javascript { .api }
137
/**
138
* Generates a random color
139
* @returns new tinycolor instance with random RGB values
140
*/
141
tinycolor.random(): tinycolor;
142
```
143
144
**Usage Examples:**
145
146
```javascript
147
// Generate single random color
148
const randomColor = tinycolor.random();
149
console.log("Random color:", randomColor.toHexString());
150
151
// Generate multiple random colors
152
const randomPalette = Array.from({length: 5}, () => tinycolor.random());
153
console.log("Random palette:", randomPalette.map(c => c.toHexString()));
154
155
// Generate random colors with constraints
156
function randomColorWithConstraints(options = {}) {
157
const {
158
minBrightness = 0,
159
maxBrightness = 255,
160
minSaturation = 0,
161
maxSaturation = 1,
162
hueRange = null
163
} = options;
164
165
let color;
166
let attempts = 0;
167
const maxAttempts = 100;
168
169
do {
170
color = tinycolor.random();
171
const hsl = color.toHsl();
172
const brightness = color.getBrightness();
173
174
const brightnessOk = brightness >= minBrightness && brightness <= maxBrightness;
175
const saturationOk = hsl.s >= minSaturation && hsl.s <= maxSaturation;
176
const hueOk = !hueRange || (hsl.h >= hueRange[0] && hsl.h <= hueRange[1]);
177
178
if (brightnessOk && saturationOk && hueOk) {
179
return color;
180
}
181
182
attempts++;
183
} while (attempts < maxAttempts);
184
185
return color; // Return last attempt if no perfect match
186
}
187
188
// Generate bright colors only
189
const brightColors = Array.from({length: 3}, () =>
190
randomColorWithConstraints({ minBrightness: 150 })
191
);
192
193
// Generate colors in blue range
194
const blueishColors = Array.from({length: 3}, () =>
195
randomColorWithConstraints({ hueRange: [200, 260] })
196
);
197
198
// Generate pastel colors
199
const pastelColors = Array.from({length: 3}, () =>
200
randomColorWithConstraints({
201
minBrightness: 180,
202
maxSaturation: 0.6
203
})
204
);
205
```
206
207
### Ratio-Based Color Creation
208
209
#### Create from Ratio Values
210
211
Creates colors using ratio values (0-1) instead of standard ranges.
212
213
```javascript { .api }
214
/**
215
* Creates a tinycolor from ratio values (0-1 range instead of 0-255 for RGB)
216
* @param color - Color object with ratio values
217
* @param opts - Optional configuration object
218
* @returns new tinycolor instance
219
*/
220
tinycolor.fromRatio(color: {r?: number, g?: number, b?: number, h?: number, s?: number, l?: number, v?: number, a?: number}, opts?: object): tinycolor;
221
```
222
223
**Usage Examples:**
224
225
```javascript
226
// RGB ratios (0-1 instead of 0-255)
227
const redRatio = tinycolor.fromRatio({r: 1, g: 0, b: 0});
228
const grayRatio = tinycolor.fromRatio({r: 0.5, g: 0.5, b: 0.5});
229
const customRatio = tinycolor.fromRatio({r: 0.8, g: 0.2, b: 0.6});
230
231
console.log("Red from ratio:", redRatio.toHexString()); // "#ff0000"
232
console.log("Gray from ratio:", grayRatio.toHexString()); // "#808080"
233
console.log("Custom from ratio:", customRatio.toHexString());
234
235
// HSL ratios
236
const blueHslRatio = tinycolor.fromRatio({h: 0.67, s: 1, l: 0.5}); // Blue
237
const orangeHslRatio = tinycolor.fromRatio({h: 0.083, s: 1, l: 0.5}); // Orange
238
239
// HSV ratios
240
const yellowHsvRatio = tinycolor.fromRatio({h: 0.167, s: 1, v: 1}); // Yellow
241
242
// With alpha ratios
243
const transparentRedRatio = tinycolor.fromRatio({r: 1, g: 0, b: 0, a: 0.5});
244
console.log("Transparent red:", transparentRedRatio.toRgbString());
245
246
// Useful for mathematical color generation
247
function generateColorFromData(value, min, max) {
248
// Normalize value to 0-1 range
249
const ratio = (value - min) / (max - min);
250
251
// Create color based on ratio (red to green gradient)
252
return tinycolor.fromRatio({
253
r: 1 - ratio, // Red decreases as value increases
254
g: ratio, // Green increases as value increases
255
b: 0,
256
a: 1
257
});
258
}
259
260
// Data visualization colors
261
const dataPoints = [10, 25, 50, 75, 90];
262
const minValue = Math.min(...dataPoints);
263
const maxValue = Math.max(...dataPoints);
264
265
const colors = dataPoints.map(value =>
266
generateColorFromData(value, minValue, maxValue)
267
);
268
269
console.log("Data colors:", colors.map(c => c.toHexString()));
270
```
271
272
## Advanced Utility Examples
273
274
### Color Space Utilities
275
276
```javascript
277
// Convert between different ratio representations
278
function convertRatios(color, fromSpace, toSpace) {
279
const tc = tinycolor(color);
280
281
switch (toSpace) {
282
case 'rgb-ratio':
283
const rgb = tc.toRgb();
284
return {r: rgb.r/255, g: rgb.g/255, b: rgb.b/255, a: rgb.a};
285
286
case 'hsl-ratio':
287
const hsl = tc.toHsl();
288
return {h: hsl.h/360, s: hsl.s, l: hsl.l, a: hsl.a};
289
290
case 'hsv-ratio':
291
const hsv = tc.toHsv();
292
return {h: hsv.h/360, s: hsv.s, v: hsv.v, a: hsv.a};
293
294
default:
295
return tc.toRgb();
296
}
297
}
298
299
// Interpolation utilities
300
function interpolateColors(color1, color2, steps, space = 'rgb') {
301
const colors = [];
302
303
for (let i = 0; i <= steps; i++) {
304
const ratio = i / steps;
305
306
switch (space) {
307
case 'hsl':
308
const hsl1 = tinycolor(color1).toHsl();
309
const hsl2 = tinycolor(color2).toHsl();
310
311
colors.push(tinycolor.fromRatio({
312
h: (hsl1.h + (hsl2.h - hsl1.h) * ratio) / 360,
313
s: hsl1.s + (hsl2.s - hsl1.s) * ratio,
314
l: hsl1.l + (hsl2.l - hsl1.l) * ratio,
315
a: hsl1.a + (hsl2.a - hsl1.a) * ratio
316
}));
317
break;
318
319
default:
320
colors.push(tinycolor.mix(color1, color2, ratio * 100));
321
}
322
}
323
324
return colors;
325
}
326
```
327
328
### Color Validation and Correction
329
330
```javascript
331
function validateAndCorrectColor(input, fallback = '#000000') {
332
const color = tinycolor(input);
333
334
if (!color.isValid()) {
335
console.warn(`Invalid color "${input}", using fallback "${fallback}"`);
336
return tinycolor(fallback);
337
}
338
339
return color;
340
}
341
342
function ensureContrast(backgroundColor, textColor, minRatio = 4.5) {
343
const bgColor = validateAndCorrectColor(backgroundColor);
344
let txtColor = validateAndCorrectColor(textColor);
345
346
const currentRatio = tinycolor.readability(bgColor, txtColor);
347
348
if (currentRatio >= minRatio) {
349
return txtColor;
350
}
351
352
// Try to adjust text color
353
const bgLuminance = bgColor.getLuminance();
354
const preferDark = bgLuminance > 0.5;
355
356
const options = preferDark
357
? ['#000000', '#333333', '#666666']
358
: ['#ffffff', '#cccccc', '#999999'];
359
360
return tinycolor.mostReadable(bgColor, options);
361
}
362
```
363
364
### Color Math Operations
365
366
```javascript
367
// Weighted color mixing
368
function weightedMix(colors, weights) {
369
if (colors.length !== weights.length) {
370
throw new Error('Colors and weights arrays must have the same length');
371
}
372
373
const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
374
375
// Convert all colors to RGB ratios
376
const rgbColors = colors.map(color => {
377
const rgb = tinycolor(color).toRgb();
378
return {
379
r: rgb.r / 255,
380
g: rgb.g / 255,
381
b: rgb.b / 255,
382
a: rgb.a
383
};
384
});
385
386
// Calculate weighted average
387
const result = rgbColors.reduce((acc, color, index) => {
388
const weight = weights[index] / totalWeight;
389
return {
390
r: acc.r + color.r * weight,
391
g: acc.g + color.g * weight,
392
b: acc.b + color.b * weight,
393
a: acc.a + color.a * weight
394
};
395
}, {r: 0, g: 0, b: 0, a: 0});
396
397
return tinycolor.fromRatio(result);
398
}
399
400
// Usage
401
const mixed = weightedMix(
402
['red', 'blue', 'green'],
403
[0.5, 0.3, 0.2]
404
);
405
406
// Color distance calculation
407
function colorDistance(color1, color2) {
408
const rgb1 = tinycolor(color1).toRgb();
409
const rgb2 = tinycolor(color2).toRgb();
410
411
// Euclidean distance in RGB space
412
const dr = rgb1.r - rgb2.r;
413
const dg = rgb1.g - rgb2.g;
414
const db = rgb1.b - rgb2.b;
415
416
return Math.sqrt(dr * dr + dg * dg + db * db);
417
}
418
419
// Find closest color in palette
420
function findClosestColor(targetColor, palette) {
421
let closest = palette[0];
422
let minDistance = colorDistance(targetColor, closest);
423
424
palette.forEach(color => {
425
const distance = colorDistance(targetColor, color);
426
if (distance < minDistance) {
427
minDistance = distance;
428
closest = color;
429
}
430
});
431
432
return {
433
color: closest,
434
distance: minDistance
435
};
436
}
437
```