js将十六进制颜色转透明度的函数
CSS颜色的表示方式一般有两种10进制与16进制,分别是【rgb(255, 100, 0)】【#FF0000】。两个16进制组合数是0-255(16*16=256)。
颜色是RGB红绿蓝三原色组成的,16进制的颜色由6位字符组成(如:FF0000,相隔重复类型也可以简写成F00),如果16进制要包含透明度必须由八位字符组成(如:FFDDAA80)。
平时css样式的透明度都是按十进制计算的,如:opacity: 0.5;与background-color: rgba(255, 100, 0, 0.8);。
10进制的255阶为不透明(0%),0阶为100%透明。所以如果要获取50%透明度,255 * 0.5 = 127.5;将127.5四舍五入再转16进制,方法如下:
function getHexOpacityColor({color = '#000',opacity = 0.5}){
opacity = Math.max(opacity,0);
opacity = Math.min(opacity,1);
color = color.replace(/\#/g,'').toUpperCase();
if(color.length === 3){
let arr = color.split('');
color = '';
for (let i = 0; i < arr.length; i++) {
color += (arr[i] + arr[i]);//将简写的3位字符补全到6位字符
}
}
let num = Math.round(255 * opacity);//四舍五入
let str = '';
let arrHex = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];//十六进制数组
while (num>0) {
let mod = num % 16;
num = (num - mod) / 16;
str = arrHex[mod] + str;
}
if(str.length == 1)str = '0' + str;
if(str.length == 0)str = '00';
return `#${color+str}`;
}
getHexOpacityColor({color:'#f00',opacity:0.5});
下面方法是0%-100%的透明度输出:
function getHexOpacity({opacity = 0.5}){
opacity = Math.max(opacity,0);
opacity = Math.min(opacity,1);
let num = Math.round(255 * opacity);//向下取整
let str = '';
let arrHex = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];//十六进制数组
while (num>0) {
let mod = num % 16;
num = (num - mod) / 16;
str = arrHex[mod] + str;
}
if(str.length == 1)str = '0' + str;
if(str.length == 0)str = '00';
return `${str}`;
}
//输出0-100的透明度(16进制)
var all = '';
for (var i = 0; i <= 100; i++) {
let opacity = i / 100;
let str = getHexOpacity({opacity});
all += `\n${i}% — ${str}`;
}
console.log(all);
0% — 00 1% — 03 2% — 05 3% — 08 4% — 0A 5% — 0D 6% — 0F 7% — 12 8% — 14 9% — 17 10% — 1A 11% — 1C 12% — 1F 13% — 21 14% — 24 15% — 26 16% — 29 17% — 2B 18% — 2E 19% — 30 |
20% — 33 21% — 36 22% — 38 23% — 3B 24% — 3D 25% — 40 26% — 42 27% — 45 28% — 47 29% — 4A 30% — 4D 31% — 4F 32% — 52 33% — 54 34% — 57 35% — 59 36% — 5C 37% — 5E 38% — 61 39% — 63 |
40% — 66 41% — 69 42% — 6B 43% — 6E 44% — 70 45% — 73 46% — 75 47% — 78 48% — 7A 49% — 7D 50% — 80 51% — 82 52% — 85 53% — 87 54% — 8A 55% — 8C 56% — 8F 57% — 91 58% — 94 59% — 96 |
60% — 99 61% — 9C 62% — 9E 63% — A1 64% — A3 65% — A6 66% — A8 67% — AB 68% — AD 69% — B0 70% — B3 71% — B5 72% — B8 73% — BA 74% — BD 75% — BF 76% — C2 77% — C4 78% — C7 79% — C9 |
80% — CC 81% — CF 82% — D1 83% — D4 84% — D6 85% — D9 86% — DB 87% — DE 88% — E0 89% — E3 90% — E6 91% — E8 92% — EB 93% — ED 94% — F0 95% — F2 96% — F5 97% — F7 98% — FA 99% — FC 100% — FF |
---|