Among all the weird desires of your clients, one of the most weird of them surely are the ones of designers. Lately i needed to fulfill a requirement that sound initially weird, detecting the name of the color by its hex code in JavaScript. Initially and after some research i found out how difficult this task was. Fortunately, with a couple of implementations in JavaScript had a lot of potential, specifically the Name That Color library.
In this article, we'll explain you how to use the JavaScript library Name that Color easily.
1. Download NTC.js
You can download the ntc.js script file from the official website here. With the NTC tool you will be able to guess the closest color according to its given code and the register in the class. It's worth to say that the art of guessing a color by its hexadecimal code its pretty tricky, as well of the appreciation of naming a color could vary as well. However, the original JS script offers a wide range of colors that may match your hex code, if it isn't registered in the class, it will return the closest color.
For more information about this project, please visit the official website here.
2. How to use
Initially, you only will need to cast the name method of the ntc object created by the library, whose initialization takes a little execution time because it will create a quite huge color palette that it will use to compare your hex code with the available data. From the instance, you will be able to use 3 methods. Of our interest is only the name
method useful:
<!-- Include name that color library -->
<script type="text/javascript" src="ntc.js"></script>
<script type="text/javascript">
// 1. You need a hex code of the color
var ColorCode = "#008559";
// 2. Rate the color using NTC
var ntcMatch = ntc.name(ColorCode);
// 3. Handle the result. The library returns an array with the identified color.
// 3.A RGB value of closest match e.g #01826B
console.log(ntcMatch[0]);
// Text string: Color name e.g "Deep Sea"
console.log(ntcMatch[1]);
// True if exact color match, a Boolean
console.log(ntcMatch[2]);
</script>
This method expects as first argument a string with a hexadecimal color code of 6 or 3 digits e.g #ffffff or #fff and returns an array with the data that you need to know according to the color guess process. The array contains 3 items respectively:
0
: the hex color of the closest color in the class.1
: the human name given to the color.2
: boolean that determines wheter the color code is exact as the name or not.
The property that you are looking for is the name key that returns an human name for the hex color code, in this case is the Deep Sea color, but it works for almost every hex color that you provide, in case that it doesn't work with your color, you will receive an array with the same 3 items, however with the following values:
0
: #000000.1
: Invalid Color: $yourHexCodeString.2
: false
Happy coding !