@amaui/utils
Version:
26 lines (21 loc) • 1.1 kB
JavaScript
import isValid from './isValid';
import clamp from './clamp';
import castParam from './castParam';
const intToHex = value => {
const hex = castParam(value).toString(16);
return hex.length === 1 ? "0".concat(hex) : hex;
};
const rgbToHex = function (value) {
let opacity_ = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
let array = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (isValid('color-rgb', value)) {
let values = value.replace(/rgb|a|\(|\s|\)/g, '').split(',').filter(Boolean); // If alpha value exists, multiply it by 255 rgb max range value
if (values[3]) values[3] = Math.round(parseFloat(values[3]) * 255);
const opacity = opacity_ !== undefined && (opacity_ > 1 ? +(opacity_ / 100).toFixed(2) : clamp(opacity_, 0, 1));
if (opacity) values.push(Math.round(parseFloat(opacity) * 255));
values = values.map(item => intToHex(item));
const [r, g, b, a] = values;
return array ? values.filter(Boolean) : "#".concat(r).concat(g).concat(b).concat(a ? a : '');
}
};
export default rgbToHex;