typescript实现16进制和rgba互转
时间: 2024-03-21 13:44:05 浏览: 242
可以通过以下代码实现 TypeScript 中的 16 进制和 RGBA 互转:
```ts
/**
* 将 16 进制颜色转为 RGBA
* @param hex 16 进制颜色字符串
* @param alpha 透明度,默认为 1
* @returns RGBA 颜色字符串
*/
function hexToRGBA(hex: string, alpha: number = 1): string {
hex = hex.replace('#', '');
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
/**
* 将 RGBA 颜色转为 16 进制颜色
* @param rgba RGBA 颜色字符串
* @returns 16 进制颜色字符串
*/
function RGBAToHex(rgba: string): string {
const match = rgba.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.\d+|\d+))?\)$/);
if (!match) {
throw new Error('Invalid input, expected RGBA color string');
}
const r = (+match[1]).toString(16).padStart(2, '0');
const g = (+match[2]).toString(16).padStart(2, '0');
const b = (+match[3]).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
```
使用示例:
```ts
const hexColor = '#ff0000';
const rgbaColor = hexToRGBA(hexColor, 0.5);
console.log(rgbaColor); // 输出:rgba(255, 0, 0, 0.5)
const rgbColor = 'rgba(255, 0, 0, 1)';
const hexColor2 = RGBAToHex(rgbColor);
console.log(hexColor2); // 输出:#ff0000
```
阅读全文