RGB to hex and hex to RGB

前端 未结 30 2834
遥遥无期
遥遥无期 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:03

    I came across this problem since I wanted to accept any color value and be able to add an opacity, so I made this quick jQuery plugin that uses the native canvas on modern browsers. Seems to work just great.

    Edit

    Turns out I can't figure out how to make it a proper jQuery plugin, so I'll just present it as a regular function.

    //accepts any value like '#ffffff', 'rgba(255,255,255,1)', 'hsl(0,100%,100%)', or 'white'
    function toRGBA( c ) {
        var
            can  = document.createElement( 'canvas' ),
            ctx  = can.getContext( '2d' );
        can.width = can.height = 1;
        ctx.fillStyle = c;
        console.log( ctx.fillStyle ); //always css 6 digit hex color string, e.g. '#ffffff'
        ctx.fillRect( 0, 0, 1, 1 ); //paint the canvas
        var
            img  = ctx.getImageData( 0, 0, 1, 1 ),
            data = img.data,
            rgba = {
                r: data[ 0 ], //0-255 red
                g: data[ 1 ], //0-255 green
                b: data[ 2 ], //0-255 blue
                a: data[ 3 ]  //0-255 opacity (0 being transparent, 255 being opaque)
            };
        return rgba;
    };
    

提交回复
热议问题