function rgbToHex(r, g, b) {
return "#" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
2012年12月3日更新
这是hexToRgb()的一个版本,它还解析了一个速记十六进制三元组,例如“#03F”:
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
alert(hexToRgb("#0033ff").g); // "51";
alert(hexToRgb("#03f").g); // "51";
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
编辑:2017年3月28日
这是另一种方法那似乎更快
function hexToRgbNew(hex) {
var arrBuff = new ArrayBuffer(4);
var vw = new DataView(arrBuff);
vw.setUint32(0,parseInt(hex, 16),false);
var arrByte = new Uint8Array(arrBuff);
return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}
function rgbToHex(r, g, b) {
if(r < 0 || r > 255) alert("r is out of bounds; "+r);
if(g < 0 || g > 255) alert("g is out of bounds; "+g);
if(b < 0 || b > 255) alert("b is out of bounds; "+b);
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");
function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
function getRGB(color){
if(color.length == 7){
var r = parseInt(color.substr(1,2),16);
var g = parseInt(color.substr(3,2),16);
var b = parseInt(color.substr(5,2),16);
return 'rgb('+r+','+g+','+b+')' ;
}
else
console.log('Enter correct value');
}
var a = getRGB('#f0f0f0');
if(!a){
a = 'Enter correct value';
}
a;
var rgb = '30,209,19';
var hex = _.reduce(rgb.split(','), function(hexAccumulator, rgbValue) {
var intColor = _.parseInt(rgbValue);
if (_.isNaN(intColor)) {
throw new Error('The value ' + rgbValue + ' was not able to be converted to int');
}
// Ensure a value such as 2 is converted to "02".
var hexColor = _.padLeft(intColor.toString(16), 2, '0');
return hexAccumulator + hexColor;
}, '#');
R = hexToR("#FFFFFF");
G = hexToG("#FFFFFF");
B = hexToB("#FFFFFF");
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
function hexToRGBA(hex, alpha){
hex = (""+hex).trim().replace(/#/g,""); //trim and remove any leading # if there (supports number values as well)
if (!/^(?:[0-9a-fA-F]{3}){1,2}$/.test(hex)) throw ("not a valid hex string"); //Regex Validator
if (hex.length==3){hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]} //support short form
var b_int = parseInt(hex, 16);
return "rgba("+[
(b_int >> 16) & 255, //R
(b_int >> 8) & 255, //G
b_int & 255, //B
alpha || 1 //add alpha if is set
].join(",")+")";
}
function rgbaHex(c,a,i){return(Array.isArray(c)||(typeof c==='string'&&/,/.test(c)))?((c=(Array.isArray(c)?c:c.replace(/[\sa-z\(\);]+/gi,'').split(',')).map(s=>parseInt(s).toString(16).replace(/^([a-z\d])$/i,'0$1'))),'#'+c[0]+c[1]+c[2]):(c=c.replace(/#/,''),c=c.length%6?c.replace(/(.)(.)(.)/,'$1$1$2$2$3$3'):c,a=parseFloat(a)||null,`rgb${a?'a':''}(${[(i=parseInt(c,16))>>16&255,i>>8&255,i&255,a].join().replace(/,$/,'')})`);}
可读版本:
function rgbaHex(c, a) {
// RGBA to Hex
if (Array.isArray(c) || (typeof c === 'string' && /,/.test(c))) {
c = Array.isArray(c) ? c : c.replace(/[\sa-z\(\);]+/gi, '').split(',');
c = c.map(s => window.parseInt(s).toString(16).replace(/^([a-z\d])$/i, '0$1'));
return '#' + c[0] + c[1] + c[2];
}
// Hex to RGBA
else {
c = c.replace(/#/, '');
c = c.length % 6 ? c.replace(/(.)(.)(.)/, '$1$1$2$2$3$3') : c;
c = window.parseInt(c, 16);
a = window.parseFloat(a) || null;
const r = (c >> 16) & 255;
const g = (c >> 08) & 255;
const b = (c >> 00) & 255;
return `rgb${a ? 'a' : ''}(${[r, g, b, a].join().replace(/,$/,'')})`;
}
}
function rgbToHex(r, g, b) {
r = Math.abs(r);
g = Math.abs(g);
b = Math.abs(b);
if ( r < 0 ) r = 0;
if ( g < 0 ) g = 0;
if ( b < 0 ) b = 0;
if ( r > 255 ) r = 255;
if ( g > 255 ) g = 255;
if ( b > 255 ) b = 255;
return '#' + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex
}).join('');
}
material.color.set( 0x660000, 0xff0000, 0xff6666 ); // red cube
我们可以从主RBG颜色创建这3个值:255,0,0
function rgbToHex(rgb) {
var hex = Number(rgb).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return hex;
};
function convertToHex(r,g,b) {
var fact = 100; // contrast
var code = '0x';
// main color
var r_hexa = rgbToHex(r);
var g_hexa = rgbToHex(g);
var b_hexa = rgbToHex(b);
// lighter
var r_light = rgbToHex(Math.floor(r+((1-(r/255))*fact)));
var g_light = rgbToHex(Math.floor(g+((1-(g/255))*fact)));
var b_light = rgbToHex(Math.floor(b+((1-(b/255))*fact)));
// darker
var r_dark = rgbToHex(Math.floor(r-((r/255)*(fact*1.5)))); // increase contrast
var g_dark = rgbToHex(Math.floor(g-((g/255)*(fact*1.5))));
var b_dark = rgbToHex(Math.floor(b-((b/255)*(fact*1.5))));
var hexa = code+r_hexa+g_hexa+b_hexa;
var light = code+r_light+g_light+b_light;
var dark = code+r_dark+g_dark+b_dark;
console.log('HEXs -> '+dark+" + "+hexa+" + "+light)
var colors = [dark, hexa, light];
return colors;
}
在您的ThreeJS代码中,只需编写:
var material = new THREE.MeshLambertMaterial();
var c = convertToHex(255,0,0); // red cube needed
material.color.set( Number(c[0]), Number(c[1]), Number(c[2]) );
import React, { Component, Fragment } from 'react';
const styles = {
display: 'block',
margin: '20px auto',
input: {
width: 170,
},
button: {
margin: '0 auto'
}
}
// test case 1
// #f0f
// test case 2
// #ff00ff
class HexToRGBColorConverter extends Component {
state = {
result: false,
color: "#ff00ff",
}
hexToRgb = color => {
let container = [[], [], []];
// check for shorthand hax string
if (color.length >= 3) {
// remove hash from string
// convert string to array
color = color.substring(1).split("");
for (let key = 0; key < color.length; key++) {
let value = color[key];
container[2].push(value);
// if the length is 3 we
// we need to add the value
// to the index we just updated
if (color.length === 3) container[2][key] += value;
}
for (let index = 0; index < color.length; index++) {
let isEven = index % 2 === 0;
// If index is odd an number
// push the value into the first
// index in our container
if (isEven) container[0].push(color[index]);
// If index is even an number
if (!isEven) {
// again, push the value into the
// first index in the container
container[0] += color[index];
// Push the containers first index
// into the second index of the container
container[1].push(container[0]);
// Flush the first index of
// of the container
// before starting a new set
container[0] = [];
}
}
// Check container length
if (container.length === 3) {
// Remove only one element of the array
// Starting at the array's first index
container.splice(0, 1);
let values = container[color.length % 2];
return {
r: parseInt(values[0], 16),
g: parseInt(values[1], 16),
b: parseInt(values[2], 16)
}
}
}
return false;
}
handleOnClick = event => {
event.preventDefault();
const { color } = this.state;
const state = Object.assign({}, this.state);
state.result = this.hexToRgb(color);
this.setState(state);
}
handleOnChange = event => {
event.preventDefault();
const { value } = event.currentTarget;
const pattern = /^([a-zA-Z0-9])/;
const boundaries = [3, 6];
if (
pattern.test(value) &&
boundaries.includes(value.length)
) {
const state = Object.assign({}, this.state);
state.color = `#${value}`;
this.setState(state);
}
}
render() {
const { color, result } = this.state;
console.log('this.state ', color, result);
return (
<Fragment>
<input
type="text"
onChange={this.handleOnChange}
style=\{\{ ...styles, ...styles.input }} />
<button
onClick={this.handleOnClick}
style=\{\{ ...styles, ...styles.button }}>
Convert hex to rgba
</button>
{
!!result &&
<div style=\{\{ textAlign: 'center' }}>
Converted { color } to { JSON.stringify(result) }
</div>
}
</Fragment>
)
}
}
export default App;
/**
* RGB color regexp
*/
export const RGB_REG_EXP = /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/;
/**
* HEX color regexp
*/
export const HEX_REG_EXP = /^#?(([\da-f]){3}|([\da-f]){6})$/i;
/**
* Converts HEX to RGB.
*
* Color must be only HEX string and must be:
* - 7-characters starts with "#" symbol ('#ffffff')
* - or 6-characters without "#" symbol ('ffffff')
* - or 4-characters starts with "#" symbol ('#fff')
* - or 3-characters without "#" symbol ('fff')
*
* @function { color: string => string } convertHexToRgb
* @return { string } returns RGB color string or empty string
*/
export const convertHexToRgb = (color: string): string => {
const errMessage = `
Something went wrong while working with colors...
Make sure the colors provided to the "PieDonutChart" meet the following requirements:
Color must be only HEX string and must be
7-characters starts with "#" symbol ('#ffffff')
or 6-characters without "#" symbol ('ffffff')
or 4-characters starts with "#" symbol ('#fff')
or 3-characters without "#" symbol ('fff')
- - - - - - - - -
Error in: "convertHexToRgb" function
Received value: ${color}
`;
if (
!color
|| typeof color !== 'string'
|| color.length < 3
|| color.length > 7
) {
console.error(errMessage);
return '';
}
const replacer = (...args: string[]) => {
const [
_,
r,
g,
b,
] = args;
return '' + r + r + g + g + b + b;
};
const rgbHexArr = color
?.replace(HEX_REG_EXP, replacer)
.match(/.{2}/g)
?.map(x => parseInt(x, 16));
/**
* "HEX_REG_EXP.test" is here to create more strong tests
*/
if (rgbHexArr && Array.isArray(rgbHexArr) && HEX_REG_EXP.test(color)) {
return `rgb(${rgbHexArr[0]}, ${rgbHexArr[1]}, ${rgbHexArr[2]})`;
}
console.error(errMessage);
return '';
};
我在用Jest做测试
color.spec.ts
describe('function "convertHexToRgb"', () => {
it('returns a valid RGB with the provided 3-digit HEX color: [color = \'fff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('fff');
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = \'#fff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('#fff');
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns a valid RGB with the provided 6-digit HEX color: [color = \'ffffff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('ffffff');
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = \'#ffffff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb(TEST_COLOR);
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns an empty string when the provided value is not a string: [color = 1234]', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
// @ts-ignore
const rgb = convertHexToRgb(1234);
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided color is too short: [color = \'FF\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('FF');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided color is too long: [color = \'#fffffff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('#fffffff');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = \'#fffffp\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('#fffffp');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided value is invalid: [color = \'*\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('*');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided value is undefined: [color = undefined]', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
// @ts-ignore
const rgb = convertHexToRgb(undefined);
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
});
tests result:
function "convertHexToRgb"
√ returns a valid RGB with the provided 3-digit HEX color: [color = 'fff']
√ returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = '#fff']
√ returns a valid RGB with the provided 6-digit HEX color: [color = 'ffffff']
√ returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = '#ffffff']
√ returns an empty string when the provided value is not a string: [color = 1234]
√ returns an empty string when the provided color is too short: [color = 'FF']
√ returns an empty string when the provided color is too long: [color = '#fffffff']
√ returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = '#fffffp']
√ returns an empty string when the provided value is invalid: [color = '*']
√ returns an empty string when the provided value is undefined: [color = undefined]
const hex = (h) => {
return h
.replace(
/^#?([a-f\d])([a-f\d])([a-f\d])$/i,
(_, r, g, b) => "#" + r + r + g + g + b + b
)
.substring(1)
.match(/.{2}/g)
.map((x) => parseInt(x, 16));
};