EN
JavaScript - calculate weighted color between indicated colors
9 points
In this article, we would like to show you how to calculate weighted color between indicated colors in JavaScript.
Runnable example:
xxxxxxxxxx
1
const calculateWeightedColor = (colors, weights) => {
2
if (colors.length !== weights.length) {
3
throw new Error('Values and weights arrays must have same size.');
4
}
5
let r = 0, g = 0, b = 0; // sums of components
6
let s = 0; // sum of weights
7
for (let i = 0; i < colors.length; ++i) {
8
const color = colors[i];
9
const weight = weights[i];
10
r += weight * color.red;
11
g += weight * color.green;
12
b += weight * color.blue;
13
s += weight;
14
}
15
return {
16
red: Math.round(r / s),
17
green: Math.round(g / s),
18
blue: Math.round(b / s)
19
};
20
};
21
22
23
// Example helpers:
24
25
const appendColor = (color) => {
26
const element = document.createElement('div');
27
element.style.display = 'inline-block';
28
element.style.width = '20px';
29
element.style.height = '20px';
30
element.style.background = `rgb(${color.red}, ${color.green}, ${color.blue})`;
31
document.body.appendChild(element);
32
};
33
34
const appendSpace = (size) => {
35
for (let i = 0; i < size; ++i) {
36
document.body.appendChild(document.createElement('br'));
37
}
38
};
39
40
41
// Example input:
42
43
const colors = [
44
{red: 23, green: 23, blue: 230},
45
{red: 23, green: 230, blue: 229},
46
{red: 23, green: 230, blue: 27},
47
{red: 229, green: 230, blue: 23},
48
{red: 230, green: 23, blue: 23}
49
];
50
51
52
// Usage example 1:
53
54
const color = calculateWeightedColor(colors, [1, 0, 0, 0, 0]);
55
56
console.log(`{red: ${color.red}, blue: ${color.green}, green: ${color.blue}}`);
57
58
59
// Usage example 2:
60
61
for (let i = 0; i < colors.length; ++i) {
62
appendColor(colors[i]); // displays input colors
63
}
64
65
appendSpace(2);
66
67
appendColor(calculateWeightedColor(colors, [1, 0, 0, 0, 0]));
68
appendColor(calculateWeightedColor(colors, [1, 1, 0, 0, 0]));
69
appendColor(calculateWeightedColor(colors, [1, 1, 1, 0, 0]));
70
appendColor(calculateWeightedColor(colors, [1, 1, 1, 1, 0]));
71
appendColor(calculateWeightedColor(colors, [1, 1, 1, 1, 1]));
72
73
appendSpace(1);
74
75
appendColor(calculateWeightedColor(colors, [1, 2, 4, 0, 0]));
76
appendColor(calculateWeightedColor(colors, [0.25, 0.5, 1, 0, 0])); // the same like [1, 2, 4, 0, 0]
77
78
appendSpace(1);
79
80
appendColor(calculateWeightedColor(colors, [0.5, 0, 0, 0, 0.7]));