How to Convert RGB to HWB
Converting RGB to HWB (Hue, Whiteness, Blackness) is a great way to translate digital screen colors into a format that mimics mixing physical paint. HWB is highly intuitive for creating monochromatic palettes, tints, and shades.
Understanding HWB
While RGB mixes red, green, and blue light, HWB starts with a base Hue on the color wheel (0-360°) and then mixes in white and black.
- Whiteness: Acts like adding white paint. It lightens the color and reduces its saturation, creating a tint.
- Blackness: Acts like adding black paint. It darkens the color, creating a shade.
If you want a pastel version of a color, you increase the Whiteness. If you want a deep, dark version, you increase the Blackness.
The Conversion Math
Converting RGB to HWB is actually simpler than converting to HSL. The Hue is calculated exactly the same way as it is in HSL (by finding the dominant RGB channel and calculating its offset on the color wheel).
The Whiteness and Blackness are very straightforward:
- Whiteness is simply the lowest value of the three RGB channels (normalized to a 0-1 scale).
- Blackness is calculated by subtracting the highest of the three RGB channels from 1 (or 100%).
Converting RGB to HWB in JavaScript
Here is how you can programmatically convert RGB values (0-255) into HWB percentages:
function rgbToHwb(r, g, b) {
// Normalize RGB to 0-1
r /= 255; g /= 255; b /= 255;
let max = Math.max(r, g, b);
let min = Math.min(r, g, b);
// Whiteness is the minimum channel
let w = min;
// Blackness is 1 minus the maximum channel
let bk = 1 - max;
let h = 0;
// Calculate Hue
if (max !== min) {
let d = max - min;
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return {
h: Math.round(h * 360),
w: Math.round(w * 100),
b: Math.round(bk * 100)
};
}