Member-only story

Generate Contrasting Text for Your Random Background Color

How to automatically generate contrasting text for your random background color in JavaScript

David Dal Busco
Better Programming
4 min readDec 23, 2019

Photo by davisco on Unsplash

I am currently developing a new application to notably improve my React Redux know-how. In this new project, users will be able to assign the color of their choice to some entities’ background. That’s why I had to find a solution to display contrasted texts.

Credits

I was looking to resolve this problem this weekend when I suddenly remembered that the Ionic Color Generator actually already solved it. I had a look at their code (you gotta love open source ❤️) and based the solution on their implementation.

I also had to implement a function to convert hex to RGB colors. For that purpose, I found a clean regular expression on Stack Overflow provided by xameeramir.

Generate a Contrasting Text

To generate a contrasting text, we are using the following formula defined by the World Wide Web Consortium (W3C) to ensure that foreground and background color combinations provide sufficient contrast when viewed by someone having color deficits or when viewed on a black-and-white screen:

((Red value X 299) + (Green value X 587) +…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

David Dal Busco
David Dal Busco

Written by David Dal Busco

Freelancer by day | Creator of Juno.build by night

Responses (1)

Write a response