Method: Sass::Script::Value::Color#initialize
- Defined in:
- lib/sass/script/value/color.rb
#initialize(attrs) ⇒ Color #initialize(rgba, [representation]) ⇒ Color
Constructs an RGB or HSL color object, optionally with an alpha channel.
RGB values are clipped within 0 and 255. Saturation and lightness values are clipped within 0 and 100. The alpha value is clipped within 0 and 1.
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/sass/script/value/color.rb', line 229
def initialize(attrs, representation = nil, allow_both_rgb_and_hsl = false)
super(nil)
if attrs.is_a?(Array)
unless (3..4).include?(attrs.size)
raise ArgumentError.new("Color.new(array) expects a three- or four-element array")
end
red, green, blue = attrs[0...3].map {|c| Sass::Util.round(c)}
@attrs = {:red => red, :green => green, :blue => blue}
@attrs[:alpha] = attrs[3] ? attrs[3].to_f : 1
@representation = representation
else
attrs = attrs.reject {|_k, v| v.nil?}
hsl = [:hue, :saturation, :lightness] & attrs.keys
rgb = [:red, :green, :blue] & attrs.keys
if !allow_both_rgb_and_hsl && !hsl.empty? && !rgb.empty?
raise ArgumentError.new("Color.new(hash) may not have both HSL and RGB keys specified")
elsif hsl.empty? && rgb.empty?
raise ArgumentError.new("Color.new(hash) must have either HSL or RGB keys specified")
elsif !hsl.empty? && hsl.size != 3
raise ArgumentError.new("Color.new(hash) must have all three HSL values specified")
elsif !rgb.empty? && rgb.size != 3
raise ArgumentError.new("Color.new(hash) must have all three RGB values specified")
end
@attrs = attrs
@attrs[:hue] %= 360 if @attrs[:hue]
@attrs[:alpha] ||= 1
@representation = @attrs.delete(:representation)
end
[:red, :green, :blue].each do |k|
next if @attrs[k].nil?
@attrs[k] = Sass::Util.restrict(Sass::Util.round(@attrs[k]), 0..255)
end
[:saturation, :lightness].each do |k|
next if @attrs[k].nil?
@attrs[k] = Sass::Util.restrict(@attrs[k], 0..100)
end
@attrs[:alpha] = Sass::Util.restrict(@attrs[:alpha], 0..1)
end
|