我正在做的是我有一个颜色和颜色数组,例如四种颜色(#0000ff(蓝色),## 000033(深蓝色),#ccccff(浅蓝色),#b20000(红色))和颜色(粉)。我需要将颜色与我的数组中最接近的颜色相匹配。在我的情况下,粉红色应与红色相匹配。我怎样才能做到这一点? 。我有一种RGB颜色,我正在转换为Hex。
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
This is working fine but now i need to match the color with the color array and pick the best color.
I have found the solution.
function getSimilarColors (color) {
var base_colors=["0000ff","000033","ccccff","b20000"];
//Convert to RGB, then R, G, B
var color_rgb = hex2rgb(color);
var color_r = color_rgb.split(',')[0];
var color_g = color_rgb.split(',')[1];
var color_b = color_rgb.split(',')[2];
//Create an emtyp array for the difference betwwen the colors
var differenceArray=[];
//Function to find the smallest value in an array
Array.min = function( array ){
return Math.min.apply( Math, array );
};
//Convert the HEX color in the array to RGB colors, split them up to R-G-B, then find out the difference between the "color" and the colors in the array
$.each(base_colors, function(index, value) {
var base_color_rgb = hex2rgb(value);
var base_colors_r = base_color_rgb.split(',')[0];
var base_colors_g = base_color_rgb.split(',')[1];
var base_colors_b = base_color_rgb.split(',')[2];
//Add the difference to the differenceArray
differenceArray.push(Math.sqrt((color_r-base_colors_r)*(color_r-base_colors_r)+(color_g-base_colors_g)*(color_g-base_colors_g)+(color_b-base_colors_b)*(color_b-base_colors_b)));
});
//Get the lowest number from the differenceArray
var lowest = Array.min(differenceArray);
//Get the index for that lowest number
var index = differenceArray.indexOf(lowest);
//Return the HEX code
return base_colors[index];
}
这是如何将hex转换为rgb
//Function to convert HEX to RGB
function hex2rgb( colour ) {
var r,g,b;
if ( colour.charAt(0) == '#' ) {
colour = colour.substr(1);
}
r = colour.charAt(0) + colour.charAt(1);
g = colour.charAt(2) + colour.charAt(3);
b = colour.charAt(4) + colour.charAt(5);
r = parseInt( r,16 );
g = parseInt( g,16 );
b = parseInt( b ,16);
return r+','+g+','+b;
}