Reputation: 2173
In my @vue/cli 4.1.1 app user enter color and I have to output color value with entered color and I wonder how can I calculate and set background color to be sure that entered color value is good visible. I mean if user entered white color(or near) background must be dark?
Thanks
Upvotes: 4
Views: 544
Reputation: 8040
You can determine the entered color to be light or dark on the basis of its luminance.
Here you can find a formula it's calculated on.
So, you can, for example, define the function isLight
like this
function isLight(color) {
// Converting hex color to rgb
const [red, green, blue] = hexToRgb(color);
// Determine luminance
const luminance = (0.299 * red + 0.587 * green + 0.114 * blue)/255;
// Returning true if color is light
return luminance > 0.5;
}
// function for converting hex colors to rgb array format
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? [
parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16)
] : null;
}
By using this function you can determine if the user color is light or dark and thus set the appropriate background
Upvotes: 1
Reputation: 5895
You can give an invert color - 255-color
for each of rgb
function bg(r, g, b) {return [255-r, 255-g, 255-b]}
if you get it in hex format, you can convert it to rgb
, then get the invert. like so:
function invert(hex){
hex = parseInt(hex.substring(1), 16);
var r = hex >> 16;
hex -= r << 16;
var g = hex >> 8;
hex -= g << 8;
var b = hex;
return `rgb(${255-r},${255-g},${255-b})`;
}
var color1 = "#eeff00";
var color2 = "#22faef";
var color3 = "#f1f1f1";
document.querySelector('#a').style = `color:${color1};background-color:${invert(color1)}`;
document.querySelector('#b').style = `color:${color2};background-color:${invert(color2)}`;
document.querySelector('#c').style = `color:${color3};background-color:${invert(color3)}`;
div {
padding: 10px;
}
<div id="a">Hello world!</div>
<div id="b">Hello world!</div>
<div id="c">Hello world!</div>
Upvotes: 1