Conversion between js hex color and rgba color

Definition of basic composition of Chen FF6600FF
#FF [red channel] 66 [green Channel] 00 [blue channel] FF [alpha channel (transparency)]

This is what it looks like when it's converted to rgba color. It's actually a more coquettish orange color

rgba(255,36,0,255)

255=parseInt('FF',16)，102=parseInt(66,16),0=parseInt('00',16)，255=parseInt('FF',16)

What is f? F is a hexadecimal number. We can convert it to decimal through parseInt ('ff ', 16). That's the principle

So it's easy to write like this

`````` /**
* 16 Base color to rgba
* @param hexColor
* @param alphaMaxVal Generally, here is 1 or 255. The default is 1. If the maximum value is 255, write 255
* @returns {*[]}
*/
hexColorToRgba(hexColor, alphaMaxVal = 1) {
hexColor = hexColor.replace("#", "");

//Used to split hexadecimal color channels
let reg = new RegExp("\\w{1,2}", "g");
//Split color channel
let rgbaArray255 = hexColor.match(reg);
rgbaArray255 = rgbaArray255.map((channel, index) => {
//Calculate the decimal value of each channel
let colorVal = parseInt(channel, 16);
if (index === 3) {
//This is the alpha channel
return Math.round(colorVal / (255 / alphaMaxVal) * 100) / 100
}
return colorVal;
});
return rgbaArray255;
}``````

If you want to add a rabg() and write another function

``````      rgba(rgbaArray) {
return "rgba(" + rgbaArray.join(",") + ")";
}``````

rgba color to hex color

`````` /**
* rgba Color to hex color to
* @param rgbaArray
* @param alphaMaxVal Generally, here is 1 or 255. The default is 1. If the maximum value is 255, write 255
* @returns {*[]}
*/
rgbaToHexColor(rgbaArray, alphaMaxVal = 1) {
//Replacement alarm number
return "#" + rgbaArray.map((chanel, index) => {
let hexNum="";
if (index === 3) {
//This is the alpha channel
hexNum= Number(Math.round(chanel * 255/alphaMaxVal)).toString(16);
}else {
//Normal channel direct conversion
hexNum=Number(chanel).toString(16)
}
return hexNum.length===1?'0'+hexNum:hexNum;//It solves the problem that the number of some channels is less than 10
}).join("");
}``````

RGBA (hexcolortorgba ("ාff6600"); / / output: RGBA (255102,0)

RGBA (hexcolortorgba ("ාff6600"); / / output: RGBA (255102,0,1)

Rgbatohexcolor ([255102,0,1]) / / output: "ff6600ff or the orange of the new year"

Tags: Front-end less

Posted on Sun, 26 Apr 2020 08:22:14 -0700 by sanch