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')); // Output: rgb(204,0,255)
console.log(hexToRgb('#CC00FF')); // Output: rgb(204,0,255)
...