I'm trying to turn the background color opposite to the font color in javascript something like this:
let search_bar_bgColor = document.getElementById("search_bgColor").value;
let search_bar_color = search_bar_bgColor.invert();
but the user can type anything from colors to rgb value, how do I convert the user input exactly opposite of itself?
CodePudding user response:
Do something like this:
function invert(color) {
let values = color.split(', ')
for (i = 0; i < 3; i ) {
let inverted = 255 - values[i] //Invert color by subtracting 255 from RGB value
console.log(inverted);
}
}
invert('255, 0, 0')
I'm sure you can set this up pretty easily with your input value.
CodePudding user response:
By 'opposite' I assume you mean most contrasting.
There is no inbuilt method to do this so you will have to devise your own and it will not be simple.
The first step is to define exacly what an opposite colour is. There is discussion of this here: How to pick good contrast RGB colors programmatically?
Once you have decided on a procedure to achieve what you want, you'll need to create a function to convert the colour. To simplify the arithmetic, the colour passed and returned to the function would represent rgb() colours (not worrying for now what color format your user entered).
One such function, based on the method to choose contrasting colours in Adobe Illustrator (discussed in the answer by Kyle Rosenbluth on the link I posted above), might look like this:
function contrastingColour(red,green,blue) {
// find the highest and lowest channel number and sum them;
const colorArray = [parseInt(red),parseInt(green),parseInt(blue)];
colorArray.sort((a, b) => a - b);
sumOfBrightestAndDimestChannel = colorArray[0] colorArray[2];
let redChannel = sumOfBrightestAndDimestChannel - red;
let greenChannel = sumOfBrightestAndDimestChannel - green;
let blueChannel = sumOfBrightestAndDimestChannel - blue;
return `rgb(${redChannel},${greenChannel},${blueChannel})`;
}
In order to apply the function to user-inputs, you will have to convert the users colour format to values for red, green, and blue. This is fraught with difficulty if you want the user to simply type something in an input as you will have to screen and convert every entry exhaustively.
A better approach would be to limit the way the user can submit their colour, allowing them full choices for rgb colors, hex colors and named colors.
For the rgb colours, present them with three drop-down menus, programatically loaded with every option 0-255 for each column.
Similarly, three drop downs for hex colours can limit choices in the range 00 to ff.
For named colours, a drop-down list of websafe colours could be constructed programmatically from available lists of every named web color e.g. https://gist.github.com/bobspace/2712980 lastly, you will need to define functions to convert hex and named colours to rgb so you can process them in your function.
Good luck.