RGB to hex and hex to RGB

前端 未结 30 3343
遥遥无期
遥遥无期 2020-11-21 06:56

How to convert colors in RGB format to hex format and vice versa?

For example, convert \'#0080C0\' to (0, 128, 192).

30条回答
  •  庸人自扰
    2020-11-21 07:29

    One-line functional HEX to RGBA

    Supports both short #fff and long #ffffff forms.
    Supports alpha channel (opacity).
    Does not care if hash specified or not, works in both cases.

    function hexToRGBA(hex, opacity) {
        return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(isFinite(opacity) ? opacity : 1).join(',') + ')';
    }
    

    examples:

    hexToRGBA('#fff')        ->  rgba(255,255,255,1)  
    hexToRGBA('#ffffff')     ->  rgba(255,255,255,1)  
    hexToRGBA('#fff', .2)    ->  rgba(255,255,255,0.2)  
    hexToRGBA('#ffffff', .2) ->  rgba(255,255,255,0.2)  
    hexToRGBA('fff', .2)     ->  rgba(255,255,255,0.2)  
    hexToRGBA('ffffff', .2)  ->  rgba(255,255,255,0.2)
    
    hexToRGBA('#ffffff', 0)  ->  rgba(255,255,255,0)
    hexToRGBA('#ffffff', .5) ->  rgba(255,255,255,0.5)
    hexToRGBA('#ffffff', 1)  ->  rgba(255,255,255,1)
    

提交回复
热议问题