Changing Text Color based on the Background in JavaScript

Colton Shawn O'Connor
2 min readApr 2, 2021

Hello again friends. While I was working on my Color Palette app, I came into an issue of readability. I wanted to add more color to my app by having a card background color match the most prominent color of an image. If you want to see how I got the color out of an image you can read my previous to blog posts. Here is house you extract the color on the frontend, and here is how you extract the color on the backend.

Now that we have the most prominent color of an image, we need to figure out a scalable number to determine if the text on top needs to be white or black. If we are working with an RGB value, we can extract a single value with the following code.

const brightness = Math.round(((parseInt(color[0]) * 299)(parseInt(color[1]) * 587) + (parseInt(color[2]) * 114)) / 1000)

This will return a number between 0 and 255, 0 being black, and 255 being white. Every number in between is a different shade of gray. Now with this you can play around with what number you think is the best to switch the text color at, but I found 150 to be just the right amount of brightness to switch the text color to black.

So now we have the means to get a brightness value, we can write the following function. If you are working in React or React Native, you can use state to set the text color, and write the following function.

function checkBrightness(color){
const brightness = Math.round(((parseInt(color[0]) * 299) + (parseInt(color[1]) * 587) + (parseInt(color[2]) * 114)) / 1000)
if(brightness < 150){
setTextColor("rgb(255,255,255)")
} else {
setTextColor("rgb(0,0,0)")
}
}

In vanilla JS you can write the following function to do pretty much the same thing, where $div is the card DOM element where the photo is, and colorArray is an array of 3 RGB values.

function checkBrightness(colorArray, $div){  const thergb = "rgb(" + colorArray[0] + "," + colorArray[1] + "," + colorArray[2] + ")";  $div.style.backgroundColor = thergb  const brightness = Math.round(((parseInt(colorArray[0]) * 299) + (parseInt(colorArray[1]) * 587) + (parseInt(colorArray[2]) * 114)) / 1000)  if(brightness < 150){
$div.style.color = "white"
} else {
$div.style.color = "black"
}
}

Now you are dynamically changing your text color! This is a great way to add some more color to your app without risking readability. If you want to check out the apps where I implemented this you can find my JavaScript implementation here, and my React Native Implementation here.

Thank you for reading. If you would like to check out any of my projects, my GitHub username is bigdumbbaby. You can also reach my at my linkedIn.

Thank You!

--

--