Class: Compass::Colors::HSL

Inherits:
Object
  • Object
show all
Defined in:
lib/compass-colors/hsl.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(h, s, l) ⇒ HSL

Returns a new instance of HSL.



52
53
54
55
56
# File 'lib/compass-colors/hsl.rb', line 52

def initialize(h, s, l)
  self.h = h
  self.s = s
  self.l = l
end

Instance Attribute Details

#hObject

Stored in degrees [0, 360)



6
7
8
# File 'lib/compass-colors/hsl.rb', line 6

def h
  @h
end

#lObject

Stored as a number from [0,1]



8
9
10
# File 'lib/compass-colors/hsl.rb', line 8

def l
  @l
end

#sObject

Stored as a number from [0,1]



8
9
10
# File 'lib/compass-colors/hsl.rb', line 8

def s
  @s
end

Class Method Details

.from_color(color) ⇒ Object



10
11
12
# File 'lib/compass-colors/hsl.rb', line 10

def self.from_color(color)
  from_rgb(*color.value)
end

.from_fractions(hue, saturation, lightness) ⇒ Object



48
49
50
# File 'lib/compass-colors/hsl.rb', line 48

def self.from_fractions(hue, saturation, lightness)
  HSL.new(360 * hue, saturation, lightness)
end

.from_rgb(r, g, b) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/compass-colors/hsl.rb', line 14

def self.from_rgb(r, g, b)
  rgb = [r,g,b]
  rgb.map!{|c| c / 255.0}
  min_rgb = rgb.min
  max_rgb = rgb.max
  delta = max_rgb - min_rgb

  lightness = (max_rgb + min_rgb) / 2.0

  if delta < 1e-5
     hue = 0
     saturation = 0
  else
     saturation = if ( lightness < 0.5 )
        delta / ( max_rgb + min_rgb )
     else
       delta / ( 2 - max_rgb - min_rgb )
     end

     deltas = rgb.map{|c| (((max_rgb - c) / 6.0) + (delta / 2.0)) / delta}

     hue = if (rgb[0] - max_rgb).abs < 1e-5
       deltas[2] - deltas[1]
     elsif (rgb[1] - max_rgb).abs < 1e-5
       ( 1.0 / 3.0 ) + deltas[0] - deltas[2]
     else
       ( 2.0 / 3.0 ) + deltas[1] - deltas[0]
     end
     hue += 1 if hue < 0
     hue -= 1 if hue > 1
   end
   from_fractions(hue, saturation, lightness)
end

Instance Method Details

#to_colorObject



58
59
60
61
62
63
64
# File 'lib/compass-colors/hsl.rb', line 58

def to_color
  m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s
  m1 = l * 2 - m2
  Sass::Script::Color.new([hue_to_rgb(m1, m2, hp + 1.0/3),
                           hue_to_rgb(m1, m2, hp),
                           hue_to_rgb(m1, m2, hp - 1.0/3)].map { |c| (c * 0xff).round })
end