Getting the Rgb Values for a CSS/HTML Named Color in JavaScript

Getting the RGB values for a CSS/HTML named color in JavaScript

Minimal JavaScript function:

function nameToRgba(name) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.fillStyle = name;
context.fillRect(0,0,1,1);
return context.getImageData(0,0,1,1).data;
}

How to properly get RGB values from 3 input ranges in HTML page

You are trying to push your rgb values as strings to your rgbToHex() function. Just convert them to integers first in your color() function using the parseInt() function and then send the converted rgb values to your rgbToHex() function.

Also, all three of your input listeners are doing the same thing so just create a separate function called say, assignRGB() and call that function when any of those three sliders' input event is invoked.

You can also further clean up your code by using the querySelectorAll() method to retrieve all three inputs and add the input listener to each one.


Check and run the following Code Snippet for a practical example of the above approach:

const rgbSliders = document.querySelectorAll('.slider');
function assignRGB() { var red = sliderRed.value; var green = sliderGreen.value; var blue = sliderBlue.value; color(red, green, blue);}
rgbSliders.forEach(function(slider){ slider.addEventListener('input', assignRGB);});
function color(r, g, b) { const x = parseInt(r); const y = parseInt(g); const z = parseInt(b);
console.log(rgbToHex(x,y,z));}
function rgbToHex(r, g, b) { return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);}
<div class="main">        <div class="slideContainer">            <input type="range" class="slider" value="0" min="0" max="255" step="1" id="sliderRed" style="background: linear-gradient(to right, black 0%, red 70%);">        </div>        <div class="slideContainer">            <input type="range" class="slider" value="0" min="0" max="255" step="1" id="sliderGreen" style="background: linear-gradient(to right, black, green 70%);">        </div>        <div class="slideContainer">            <input type="range" class="slider" value="0" min="0" max="255" step="1" id="sliderBlue" style="background: linear-gradient(to right, black, blue 70%);">        </div>    </div>

Get color name by HEX or RGB

You can use Name that Color.

Example:

let result = ntc.name('#6195ed');

let rgb_value = result[0]; // #6495ed : RGB value of closest match
let specific_name = result[1]; // Cornflower Blue : Color name of closest match
let is_exact_match = result[2]; // false : True if exact color match

There is also a variation of Name that Color that includes additional parameters:

http://www.color-blindness.com/color-name-hue-tool/js/ntc.js

Example:

let result = ntc.name('#6195ed');

let rgb_value = result[0]; // #6495ed : RGB value of closest match
let specific_name = result[1]; // Cornflower Blue : Color name of closest match
let shade_value = result[2]; // #0000ff : RGB value of shade of closest match
let shade_name = result[3]; // Blue : Color name of shade of closest match
let is_exact_match = result[4]; // false : True if exact color match

Javascript function to convert color names to hex codes

No, but using the list here you could create one. Something like this:

function colourNameToHex(colour)
{
var colours = {"aliceblue":"#f0f8ff","antiquewhite":"#faebd7","aqua":"#00ffff","aquamarine":"#7fffd4","azure":"#f0ffff",
"beige":"#f5f5dc","bisque":"#ffe4c4","black":"#000000","blanchedalmond":"#ffebcd","blue":"#0000ff","blueviolet":"#8a2be2","brown":"#a52a2a","burlywood":"#deb887",
"cadetblue":"#5f9ea0","chartreuse":"#7fff00","chocolate":"#d2691e","coral":"#ff7f50","cornflowerblue":"#6495ed","cornsilk":"#fff8dc","crimson":"#dc143c","cyan":"#00ffff",
"darkblue":"#00008b","darkcyan":"#008b8b","darkgoldenrod":"#b8860b","darkgray":"#a9a9a9","darkgreen":"#006400","darkkhaki":"#bdb76b","darkmagenta":"#8b008b","darkolivegreen":"#556b2f",
"darkorange":"#ff8c00","darkorchid":"#9932cc","darkred":"#8b0000","darksalmon":"#e9967a","darkseagreen":"#8fbc8f","darkslateblue":"#483d8b","darkslategray":"#2f4f4f","darkturquoise":"#00ced1",
"darkviolet":"#9400d3","deeppink":"#ff1493","deepskyblue":"#00bfff","dimgray":"#696969","dodgerblue":"#1e90ff",
"firebrick":"#b22222","floralwhite":"#fffaf0","forestgreen":"#228b22","fuchsia":"#ff00ff",
"gainsboro":"#dcdcdc","ghostwhite":"#f8f8ff","gold":"#ffd700","goldenrod":"#daa520","gray":"#808080","green":"#008000","greenyellow":"#adff2f",
"honeydew":"#f0fff0","hotpink":"#ff69b4",
"indianred ":"#cd5c5c","indigo":"#4b0082","ivory":"#fffff0","khaki":"#f0e68c",
"lavender":"#e6e6fa","lavenderblush":"#fff0f5","lawngreen":"#7cfc00","lemonchiffon":"#fffacd","lightblue":"#add8e6","lightcoral":"#f08080","lightcyan":"#e0ffff","lightgoldenrodyellow":"#fafad2",
"lightgrey":"#d3d3d3","lightgreen":"#90ee90","lightpink":"#ffb6c1","lightsalmon":"#ffa07a","lightseagreen":"#20b2aa","lightskyblue":"#87cefa","lightslategray":"#778899","lightsteelblue":"#b0c4de",
"lightyellow":"#ffffe0","lime":"#00ff00","limegreen":"#32cd32","linen":"#faf0e6",
"magenta":"#ff00ff","maroon":"#800000","mediumaquamarine":"#66cdaa","mediumblue":"#0000cd","mediumorchid":"#ba55d3","mediumpurple":"#9370d8","mediumseagreen":"#3cb371","mediumslateblue":"#7b68ee",
"mediumspringgreen":"#00fa9a","mediumturquoise":"#48d1cc","mediumvioletred":"#c71585","midnightblue":"#191970","mintcream":"#f5fffa","mistyrose":"#ffe4e1","moccasin":"#ffe4b5",
"navajowhite":"#ffdead","navy":"#000080",
"oldlace":"#fdf5e6","olive":"#808000","olivedrab":"#6b8e23","orange":"#ffa500","orangered":"#ff4500","orchid":"#da70d6",
"palegoldenrod":"#eee8aa","palegreen":"#98fb98","paleturquoise":"#afeeee","palevioletred":"#d87093","papayawhip":"#ffefd5","peachpuff":"#ffdab9","peru":"#cd853f","pink":"#ffc0cb","plum":"#dda0dd","powderblue":"#b0e0e6","purple":"#800080",
"rebeccapurple":"#663399","red":"#ff0000","rosybrown":"#bc8f8f","royalblue":"#4169e1",
"saddlebrown":"#8b4513","salmon":"#fa8072","sandybrown":"#f4a460","seagreen":"#2e8b57","seashell":"#fff5ee","sienna":"#a0522d","silver":"#c0c0c0","skyblue":"#87ceeb","slateblue":"#6a5acd","slategray":"#708090","snow":"#fffafa","springgreen":"#00ff7f","steelblue":"#4682b4",
"tan":"#d2b48c","teal":"#008080","thistle":"#d8bfd8","tomato":"#ff6347","turquoise":"#40e0d0",
"violet":"#ee82ee",
"wheat":"#f5deb3","white":"#ffffff","whitesmoke":"#f5f5f5",
"yellow":"#ffff00","yellowgreen":"#9acd32"};

if (typeof colours[colour.toLowerCase()] != 'undefined')
return colours[colour.toLowerCase()];

return false;
}

Convert rgb color to closest valid CSS3 color name

Here you are. The function itself is pure JS. Only test function uses jQuery.
Colors are defined in an array of structures, because you said you want to match to about 10 specific colors only. Most of the code is for presentation.

Function findClosestColorHex takes as parameter hex value such as '#FF0000', while findClosestColorRGB takes 3 separate integers for R, G, B. Both functions take the color table as parameter, so it can be swaped if needed, but if you are going to use one fixed table, you can change this.

In some combinations the result is not perfect because the colors that I have defined in array are only 16 basic colors.

var ColorTable = [
{name:'black', hex: '#000000'},
{name:'silver', hex: '#C0C0C0'},
{name:'gray', hex: '#808080'},
{name:'white', hex: '#FFFFFF'},
{name:'maroon', hex: '#800000'},
{name:'red', hex: '#FF0000'},
{name:'purple', hex: '#800080'},
{name:'fuchsia', hex: '#FF00FF'},
{name:'green', hex: '#008000'},
{name:'lime', hex: '#00FF00'},
{name:'olive', hex: '#808000'},
{name:'yellow', hex: '#FFFF00'},
{name:'navy', hex: '#000080'},
{name:'blue', hex: '#0000FF'},
{name:'teal', hex: '#008080'},
{name:'aqua', hex: '#00FFFF'}
];

Hex2RGB = function(hex) {
if (hex.lastIndexOf('#') > -1) {
hex = hex.replace(/#/, '0x');
} else {
hex = '0x' + hex;
}
var r = hex >> 16;
var g = (hex & 0x00FF00) >> 8;
var b = hex & 0x0000FF;
return {r:r, g:g, b:b};
};

function findClosestColorHex(hex, table)
{
var rgb = Hex2RGB(hex);
var delta = 3 * 256*256;
var temp = {r:0, g:0, b:0};
var nameFound = 'black';

for(i=0; i<table.length; i++)
{
temp = Hex2RGB(table[i].hex);
if(Math.pow(temp.r-rgb.r,2) + Math.pow(temp.g-rgb.g,2) + Math.pow(temp.b-rgb.b,2) < delta)
{
delta = Math.pow(temp.r-rgb.r,2) + Math.pow(temp.g-rgb.g,2) + Math.pow(temp.b-rgb.b,2);
nameFound = table[i].name;
}
}
return nameFound;
}

function findClosestColorRGB(r, g, b, table)
{
var rgb = {r:r, g:g, b:b};
var delta = 3 * 256*256;
var temp = {r:0, g:0, b:0};
var nameFound = 'black';

for(i=0; i<table.length; i++)
{
temp = Hex2RGB(table[i].hex);
if(Math.pow(temp.r-rgb.r,2) + Math.pow(temp.g-rgb.g,2) + Math.pow(temp.b-rgb.b,2) < delta)
{
delta = Math.pow(temp.r-rgb.r,2) + Math.pow(temp.g-rgb.g,2) + Math.pow(temp.b-rgb.b,2);
nameFound = table[i].name;
}
}
return nameFound;
}

//alert(findClosestColor('#884455', ColorTable));

// Example code

$('document').ready(function(){

$('#slider_r').val(0);
$('#slider_g').val(0);
$('#slider_b').val(0);

function ReCalc()
{
$('#selected_color').css('background-color', 'rgb('+$('#slider_r').val()+', '+$('#slider_g').val()+', '+$('#slider_b').val()+')');
var ret = findClosestColorRGB($('#slider_r').val(), $('#slider_g').val(), $('#slider_b').val(), ColorTable);
$('#matched_color').css('background-color', ret);
$('#color_name').html(ret);
}

$('#slider_r').change(function(){
$('#value_r').val($('#slider_r').val());
ReCalc();
});
$('#slider_g').change(function(){
$('#value_g').val($('#slider_g').val());
ReCalc();
});
$('#slider_b').change(function(){
$('#value_b').val($('#slider_b').val());
ReCalc();
});

});
.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'> </span><br>
Matched: <span id='matched_color' class='color-field'> </span><span id="color_name"> </span>

Get a color component from an rgb string in Javascript?

NOTE - We're all on board with the regex ate my brains and kicked my dog attitude, but the regex version just seems the better method. My opinion. Check it out.

Non-regex method:

var rgb = 'rgb(200, 12, 53)';

rgb = rgb.substring(4, rgb.length-1)
.replace(/ /g, '')
.split(',');

console.log(rgb);

http://jsfiddle.net/userdude/Fg9Ba/

Outputs:

["200", "12", "53"]

Or... A really simple regex:

EDIT: Ooops, had an i in the regex for some reason.

var rgb = 'rgb(200, 12, 53)';

rgb = rgb.replace(/[^\d,]/g, '').split(',');

console.log(rgb);

http://jsfiddle.net/userdude/Fg9Ba/2



Related Topics



Leave a reply



Submit