I am trying to get complementary colors with JavaScript, but I can't find what I need. I looked here, but for values like #000000
, and #142814
, they just return themselves. For the first value, I feel like it would make sense to get #FFFFFF
. Is there a function which would work like this?
Asked
Active
Viewed 725 times
1
1 Answers
0
You could use the difference from 224 - 1 and the value of the color and for shorter colors the difference of 212 - 1 and the value of the color.
function getComplementaryColor(color) {
var c = color.slice(1),
i = parseInt(c, 16),
v = ((1 << 4 * c.length) - 1 - i).toString(16);
while (v.length < c.length) {
v = '0' + v;
}
return '#' + v;
}
console.log(getComplementaryColor('#142814'));
console.log(getComplementaryColor('#000000'));
console.log(getComplementaryColor('#111111'));
console.log(getComplementaryColor('#ffffff'));
console.log(getComplementaryColor('#39f'));
console.log(getComplementaryColor('#000'));
console.log(getComplementaryColor('#111'));
console.log(getComplementaryColor('#fff'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Nina Scholz
- 376,160
- 25
- 347
- 392