Transform RGB values to the nearest valid CSS3 color name

I'm trying to convert an RGB value received using JavaScript to the closest valid CSS3 color name. While I found a Python solution, I'm struggling to translate it into JavaScript.

The purpose behind this conversion is to restrict the number of possible colors to around 10.

Convert RGB color to English color name, such as 'green'

Answer №1

Displaying below is a simple JavaScript function without any dependencies, while only the testing function utilizes jQuery for functionality. A collection of colors is stored in an array of objects since you mentioned a specific requirement to match around 10 predefined colors. The majority of the code focuses on visual representation.

The findClosestColorHex function accepts a hex value such as '#FF0000', whereas findClosestColorRGB takes three separate integers representing R, G, and B values. Both functions expect the color table as a parameter, allowing for easy customization if necessary, yet can be hardcoded if usage with a fixed set of colors is preferred.

In certain scenarios, the outcome may not be exact due to the limited palette defined in the color array comprising only 16 fundamental shades.

var ColorTable = [
{name:'black', hex: '#000000'},
{name:'silver', hex: '#C0C0C0'},
{name:'gray', hex: '#808080'},
...
{name:'aqua', hex: '#00FFFF'}
]; 
...
.color-field {
  display: inline-block;
  width: 200px;
  height: 50px;
  background-color: #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
R: <input id="slider_r" type="range" min="0" max="255" step="0"/> <input type=text id="value_r" value='0'><br>
G: <input id="slider_g" type="range" min="0" max="255" step="0"/> <input type=text id="value_g" value='0'><br>
B: <input id="slider_b" type="range" min="0" max="255" step="0"/> <input type=text id="value_b" value='0'><br>
<br>
Selected: <span id='selected_color' class='color-field'>&nbsp;</span><br>
Matched: <span id='matched_color' class='color-field'>&nbsp;</span><span id="color_name">&nbsp;</span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for concealing an input IP Address in React

Looking for suggestions on an IP Address mask input solution. The format might vary between 999.99.999.99 and 99.9.99.9, but react-input-mask does not support varying lengths. Any recommendations? ...

What is the most effective way to view all globally installed npm packages on my device?

While it's easy to check local dependencies in the package.json file, I'm curious about how one can identify the global packages that are currently installed on a Windows machine using npm. ...

Encountering the error message "TypeError: Cannot read property 'filename' of undefined" while attempting to run the `npm start` command

I came across a lengthy but insightful post that explains how to set up a web application using the following technology stack: es 6 node + express handlebars react + react router webpack + babel You can find the sample code here. I have been followi ...

Element that remains fixed within an element that cannot be scrolled

I am facing a challenge where I have a button nested inside a section that needs to maintain a fixed position within the parent container ('.container') while scrolling through the page. The catch is that the section itself does not scroll and ca ...

What are the steps to conducting a search on mongodb?

My document list is shown below [{"userId": "1", "text": "National security is of utmost importance"}, {"userId": "2", "text": "We must ensure a strong defense while upholding civil ...

Update the content of a div on the WordPress homepage with the click of a button

Hey there, I'm currently working on customizing the Boutique theme for a website. My goal is to add two buttons to the home page that will display different sets of products when clicked. I've been attempting to use the visibility property, but h ...

Send information through a form by utilizing a personalized React hook

I'm having difficulty understanding how to implement a hook for submitting a form using fetch. Currently, this is what I have. The component containing the form: const MyForm = (): ReactElement => { const [status, data] = useSubmitForm('h ...

What is the best way to link a datepicker to every row in a table with a shared ID?

Having an issue with the JavaScript function that attaches a date picker to each row of a dynamically created table. When I add an additional row to the table, the date picker in that row appears disabled and is not functional. <script> $(document ...

How to improve page element hiding performance on Android and iOS using jQuery user agent detection?

I've recently started using GoNative, a service that helps me create iOS and Android apps from my website located at GoNative apps come with user agent detection capabilities, which I've explored in this article: To hide specific page elements ...

"What is the best way to verify the presence of a number in my arguments using Node.js and Discord.js

const Discord = require('discord.js'); var connection = require('../index.js'); exports.run = (bot, message, args) => { var id = args[0]; var nome = args[1]; var sobrenome = args[2]; let verificarId = (id) => ...

Is there a way to eliminate a style from the final element of a list?

I have just completed a project that looks similar to this: I am wondering if there is a way to remove the line at the end of the last column? (it's within a PHP while loop) Here is the code snippet: <div style="border-bottom: 1px solid #cdc ...

Trouble with filtering in the Bootstrap table control feature

Incorporating the Filter Control extension with my bootstrap table is my goal. On the server side, I am utilizing django as the framework. The necessary CSS and JS files that I have included are: {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_jav ...

Unable to set the value of `this` when defining a string prototype

Having trouble assigning a new value to the this keyword within a string prototype definition. function testfunction(thisValue) { thisValue = thisValue || this; thisValue = "new test"; console.log(thisValue); this = thisValue; // ...

What is the best way to merge 60 related jquery functions into a unified function?

I designed a webpage that serves as an extensive checklist. When you click on the edit button for a checklist item, a modal window opens up. This modal window contains a radio button to indicate whether any issues were found during the check. If "Yes" is s ...

I am looking to create a unique object by searching for key-value pairs in an array containing 'n' number of objects, using either lodash or typescript

Here is my plan: We have an array of objects retrieved from the database. Let's focus on one item: this.usersObj. @Input() inlinetext: string; <<-- This represents the input field from the UI public usersObj: string[]; <<-- Type definit ...

Using the arrow keys to navigate through a list of items without using jQuery

Exploring ways to develop a basic autocomplete feature without relying on third-party dependencies has been my recent project. So far, I have managed to populate a results list using an ajax call and complete fields with mouse onclick events for each optio ...

What is the best way to avoid looping through duplicate keys in a JSON using Javascript?

I have been struggling to find a solution to a basic question on my own, despite my attempts. I apologize in advance for my inability to find the answer. The issue I am facing is with a JSON object that contains multiple keys with the same name, for examp ...

How to apply a CSS class to an element when hovering in Vue, without the need for data

Within a Vue component, there exists a menu structured as follows: <ul class="menu-outer-wrapper"> <li><a href="/foo-1">Foo 1</a></li> <li class="has-children"> <a href="/foo ...

Testing URL Parameters in JEST with an API

Seeking integration tests using Jest for an API endpoint. Here's the specific endpoint: http://localhost/universities/ucla/class/2013/studentalis/johndoe. When tested with a put request, it returns 201 on Postman. However, the testing encountered a t ...

I am attempting to grasp the concepts presented in this TypeScript code snippet

My template is displaying posts like this: <div class="card mb-3" *ngFor="let post of posts"> <div class="card-body"> <h5 class="card-title">{{post.title}}</h5> <p class="card-text">{{post.body}}</p> <b ...