Rohan Shewale's Blog

Simple Color Converter

It was Wednesday night and I had nothing amazing to do, and I had somehow landed on w3school’s color converter calculator page, they had mentioned their color converter library which got me thinking who will use this, but I was soon diverged and had this idea of a simple minimalist color converter with full screen preview, of course many may had made something similar; my approach was to create with no external support or any library dependency.

I made a simple color convert for HEX code to RGB and vice versa, there might not be a major need or use of this kind of tool but it was fun to make, specially because of regex.

For color input and output result I just added two text inputs with horizontal & vertical center align, and had the recorded color set to background of a wrapper.

Using event listeners input fields on value changed, the values are passed to rgb2hex() and hex2rgb() functions respectively. Switch-case statements & regular expressions were used for error handling and to support multiple input formats (eg. hex values with and without ‘#’).

The only thing that bugged me was the text color which should had depend on the background, there were many solutions to this one but I used this formula —

 brightness = (r *299 + g * 587 + b * 114) / 1000 ;

The r,g, and b values are of the background, if brightness is less than 125 than its a dark background else a lighter shade, thus text color property is changed based on background color.

querySelectorAll() is just so much better selector, you can specify id, class or tag to select the element.


All in all, this was a beautiful minimalist and small tool.

I will do try to add more color formats in future.

Live Preview link : Color Convert

Source code link: Github

Article Publish Date: November 29, 2016