Hex与rgb(a)互相转换

JavaScript 2017-03-07 hex,rgb,rgba

hex与rgb都能代表颜色,使用效果上一样的,但有时需要做一些计算时就需要转化,特别是hex转rgb后做一些计算,比如颜色拾取器等等。

hex转rgb

function hexToRgb(hex) {
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? 'rgb(' + [
            parseInt(result[1], 16),
            parseInt(result[2], 16),
            parseInt(result[3], 16)
        ].join(',') + ')' : hex;
}

console.log(hexToRgb('#C0F')); // rgb(204,0,255)
console.log(hexToRgb('#CC00FF')); // rgb(204,0,255)

hex转rgba

其实hex没有包含alpha通道,所以可以通过传入参数来实现

function hexToRgba(hex, opacity) {
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    opacity = opacity >= 0 && opacity <= 1 ? Number(opacity) : 1;
    return result ? 'rgba(' + [
            parseInt(result[1], 16),
            parseInt(result[2], 16),
            parseInt(result[3], 16),
            opacity
         ].join(',') + ')' : hex;
}

console.log(hexToRgba('#C0F')); // rgb(204,0,255,1)
console.log(hexToRgba('#CC00FF', 0.3)); // rgb(204,0,255,0.3)

rgb转hex

function rgbToHex(rgb) {
    var bg = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return ("#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3])).toUpperCase();
}

console.log(rgbToHex('rgb(204,0,255)')); // #CC00FF

rgba转hex

由于hex没有alpha通道,所以其实是放弃alpha通道,只能用rgb转hex

function rgbaToHex(rgba) {
    var bg = rgba.match(/^rgb\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(\d|(\.[1-9]{1,2})))\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return ("#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3])).toUpperCase();
}

console.log(rgbaToHex('rgb(204,0,255,1)')); // #CC00FF
console.log(rgbaToHex('rgb(204,0,255,0.1)')); // #CC00FF

 

文字链接:《Hex与rgb(a)互相转换

文章地址:http://www.qttc.net/201703477.html

除非标注,琼台博客所有博文均为原创,转载请加文字链接注明来源

乳名?小名?昵称?网名?均可

email,放心,我不会给你乱投广告的

想获得回访就把你的站点URL写上(没有留空)

[NOTICE]木要投放广告
[NOTICE]木要骂人,说不该说的话
[NOTICE]自由言论,但要遵纪守法

Comments 0

    Hi,你想第一个做沙发么?