Hàm rgbToHex nhận object {red, green, blue}, trả về chuỗi hex #RRGGBB.
Mã thực hiện
const rgbColor = { red: 0, green: 51, blue: 155 };
function rgbToHex({ red: r, green: g, blue: b }) {
const prefix = '#';
const hex = prefix + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
return hex;
}
console.log(rgbToHex(rgbColor));
Kết quả
#00339b