Module: ColorContrastCalc::Utils::Hwb

Included in:
ColorContrastCalc::Utils
Defined in:
lib/color_contrast_calc/utils.rb

Constant Summary collapse

HWB_UPPER_LIMIT =
[360, 100, 100].freeze

Instance Method Summary collapse

Instance Method Details

#hex_to_hwb(hex_code) ⇒ Array<Float>

Convert hex color code to an HWB value.

Parameters:

  • hex_code (String)

    Hex color code such as “#ffff00”

Returns:

  • (Array<Float>)

    HWB value represented as an array of numbers



305
306
307
# File 'lib/color_contrast_calc/utils.rb', line 305

def hex_to_hwb(hex_code)
  rgb_to_hwb(Utils.hex_to_rgb(hex_code))
end

#hwb_to_hex(hwb) ⇒ String

Convert an HWB value to hex color code.

Parameters:

  • hwb (Array<Float>)

    HWB value represented as an array of numbers

Returns:

  • (String)

    Hex color code such as “#ffff00”



280
281
282
# File 'lib/color_contrast_calc/utils.rb', line 280

def hwb_to_hex(hwb)
  rgb_to_hex(hwb_to_rgb(hwb))
end

#hwb_to_rgb(hwb) ⇒ Array<Integer>

Convert an HWB value to an RGB value.

Parameters:

  • hwb (Array<Float>)

    HWB value represented as an array of numbers

Returns:

  • (Array<Integer>)

    RGB value represented as an array of integers



265
266
267
268
269
270
271
272
# File 'lib/color_contrast_calc/utils.rb', line 265

def hwb_to_rgb(hwb)
  hue, white, black = normalize_hwb(hwb)
  rgb = Utils.hsl_to_rgb([hue, 100, 50])

  rgb.map do |c|
    ((c * (1.0 - white - black)) + white * 255).round
  end
end

#rgb_to_hwb(rgb) ⇒ Array<Float>

Convert an RGB value to an HWB value.

Parameters:

  • rgb (Array<Integer>)

    RGB value represented as an array of integers

Returns:

  • (Array<Float>)

    HWB value represented as an array of numbers



291
292
293
294
295
296
297
# File 'lib/color_contrast_calc/utils.rb', line 291

def rgb_to_hwb(rgb)
  # https://www.w3.org/TR/2020/WD-css-color-4-20201112/
  hsl = Utils.rgb_to_hsl(rgb)
  white = rgb.min
  black = 255 - rgb.max
  [hsl[0], white * 100 / 255.0, black * 100 / 255.0]
end

#valid_hwb?(hwb) ⇒ true, false

Check if a given array is a valid representation of HWB color.

Parameters:

  • hwb (Array<Float>)

    HWB value represented as an array of numbers

Returns:

  • (true, false)

    true if a valid HWB value is passed



315
316
317
318
319
# File 'lib/color_contrast_calc/utils.rb', line 315

def valid_hwb?(hwb)
  hwb.length == 3 && hwb.each_with_index.all? do |c, i|
    c.is_a?(Numeric) && c >= 0 && c <= HWB_UPPER_LIMIT[i]
  end
end