rgba转hex,hex转rgba

export const rgbaToHex = rgba => {
    if (typeof rgba === 'string') {
        if (rgba.includes('rgb')) {
            rgba = rgba.replace(/rgba?\(|\)/g, '').split(',').map(Number)
        }
    }
    if (!Array.isArray(rgba) || rgba.length < 3 || rgba.length > 4) {
        throw new Error('Invalid RGBA format')
    }
    const r = rgba[0].toString(16).padStart(2, '0')
    const g = rgba[1].toString(16).padStart(2, '0')
    const b = rgba[2].toString(16).padStart(2, '0')
    const a = rgba[3] !== undefined ? Math.round(rgba[3] * 255).toString(16).padStart(2, '0') : ''
    return `#${r}${g}${b}${a}`
}
export const hexToRgba = (hex, alpha = 1) => {
    hex = hex.replace('#', '')
    if (hex.length === 3) {
        hex = hex.split('').map(c => c + c).join('')
    }
    const [r, g, b] = [0, 2, 4].map(i => parseInt(hex.slice(i, i + 2), 16))
    const a = hex.length === 8 ? (parseInt(hex.slice(6, 8), 16) / 255).toFixed(2) : alpha
    return `rgba(${r}, ${g}, ${b}, ${a})`
}

// rgbaToHex('#fff') // #ffffff
// rgbaToHex('rgba(255, 255, 255, 0.5)') // #ffffff80
// rgbaToHex('rgb(255, 255, 255)') // #ffffff

// hexToRgba('#fff') // rgba(255, 255, 255, 1)
// hexToRgba('#ffffff80') // rgba(255, 255, 255, 0.50)
// hexToRgba('#fff', 0.5) // rgba(255, 255, 255, 0.50)

问ai得来的,作为记录

posted @ 2025-05-21 15:26  好吃么  阅读(44)  评论(0)    收藏  举报