Class: SC.Color
Extends
SC.Copyable, SC.Error, SC.Object.
Represents a color, and provides methods for manipulating it. Maintains underlying rgba values, and includes support for colorspace conversions between rgb and hsl.
For instructions on using SC.Color
to color a view, see "SC.Color and SC.View"
below.
Basic Use
You can create a color from red, green, blue and alpha values, with:
SC.Color.create({
r: 255,
g: 255,
b: 255,
a: 0.5
});
All values are optional; the default is black. You can also create a color from any valid CSS string, with:
SC.Color.from('rgba(255, 255, 255, 0.5)');
The best CSS value for the given color in the current browser is available at the
bindable property cssText
. (This will provide deprecated ARGB values for older
versions of IE; see "Edge Case: Supporting Alpha in IE" below.) (Calling
SC.Color.from
with an undefined or null value is equivalent to calling it with
'transparent'
.)
Once created, you can manipulate a color by settings its a, r, g or b values,
or setting its cssText
value (though be careful of invalid values; see "Error
State" below).
Math
SC.Color
provides three methods for performing basic math: sub
for subtraction,
add
for addition, and mult
for scaling a number via multiplication.
Note that these methods do not perform any validation to ensure that the underlying
rgba values stay within the device's gamut (0 to 255 on a normal screen, and 0 to 1
for alpha). For example, adding white to white will result in r, g and b values of
510, a nonsensical value. (The cssText
property will, however, correctly clamp the
component values, and the color will output #FFFFFF.) This behavior is required
for operations such as interpolating between colors (see "SC.Color and SC.View"
below); it also gives SC.Color
more predictable math, where A + B - B = A, even if
the intermediate (A + B) operation results in underlying values outside of the normal
gamut.
(The class method SC.Color.clampToDeviceGamut
is used to clamp r, g and b values to the
standard 0 - 255 range. If your application is displaying on a screen with non-standard
ranges, you may need to override this method.)
SC.Color
and SC.View
Hooking up an instance of SC.Color
to SC.View
#backgroundColor is simple, but like all
uses of backgroundColor
, it comes with moderate performance implications, and should
be avoided in cases where regular CSS is sufficient, or where bindings are unduly
expensive, such as in rapidly-scrolling ListViews.
Use the following code to tie a view's background color to an instance of SC.Color.
Note
that you must add backgroundColor
to displayProperties
in order for your view to update
when the it changes; for performance reasons it is not included by default.
SC.View.extend({
color: SC.Color.from({'burlywood'}),
backgroundColorBinding: SC.Binding.oneWay('*color.cssText'),
displayProperties: ['backgroundColor']
})
You can use this to implement a simple cross-fade between two colors. Here's a basic example (again, note that when possible, pure CSS transitions will be substantially more performant):
SC.View.extend({
displayProperties: ['backgroundColor'],
backgroundColor: 'cadetblue',
fromColor: SC.Color.from('cadetblue'),
toColor: SC.Color.from('springgreen'),
click: function() {
// Cancel previous timer.
if (this._timer) this._timer.invalidate();
// Figure out whether we're coming or going.
this._forward = !this._forward;
// Calculate the difference between the two colors.
var fromColor = this._forward ? this.fromColor : this.toColor,
toColor = this._forward ? this.toColor : this.fromColor;
this._deltaColor = toColor.sub(fromColor);
// Set the timer.
this._timer = SC.Timer.schedule({
target: this,
action: '_tick',
interval: 15,
repeats: YES,
until: Date.now() + 500
});
},
_tick: function() {
// Calculate percent of time elapsed.
var started = this._timer.startTime,
now = Date.now(),
until = this._timer.until,
pct = (now - started) / (until - started);
// Constrain pct.
pct = Math.min(pct, 1);
// Calculate color.
var fromColor = this._forward ? this.fromColor : this.toColor,
toColor = this._forward ? this.toColor : this.fromColor,
deltaColor = this._deltaColor,
currentColor = fromColor.add(deltaColor.mult(pct));
// Set.
this.set('backgroundColor', currentColor.get('cssText'));
}
})
Error State
If you call SC.Color.from
with an invalid value, or set cssText
to an invalid
value, the color object will go into error mode, with isError
set to YES
and
errorValue
containing the invalid value that triggered it. A color in error mode
will become transparent, and you will be unable to modify its r, g, b or a values.
To reset a color to its last-good values (or, if none, to black), call its reset
method. Setting cssText
to a valid value will also recover the color object to a
non-error state.
Edge Case: Supporting Alpha in IE
Supporting the alpha channel in older versions of IE requires a little extra work.
The bindable cssText
property will return valid ARGB (e.g. #99FFFFFF) when it
detects that it's in an older version of IE which requires it, but unfortunately you
can't simply plug that value into background-color
. The following code will detect
this case and provide the correct CSS snippet:
// This hack disables ClearType on IE!
var color = SC.Color.from('rgba(0, 0, 0, .5)').get('cssText'),
css;
if (SC.Color.supportsARGB) {
var gradient = "progid:DXImageTransform.Microsoft.gradient";
css = ("-ms-filter:" + gradient + "(startColorstr=%@1,endColorstr=%@1);" +
"filter:" + gradient + "(startColorstr=%@1,endColorstr=%@1)" +
"zoom: 1").fmt(color);
} else {
css = "background-color:" + color;
}
Defined in: color.js
Field Summary
- cssText
- errorValue
- hue
- isError
- SC.Color.KEYWORDS
- luminosity
- original
- saturation
- SC.Color.supportsArgb
- SC.Color.supportsRgba
- validCssText
- Fields borrowed from SC.Object:
- concatenatedProperties, isDestroyed, isObject, nextProperty, object, property, target, toInvalidate
- Fields borrowed from SC.Observable:
- isObservable
- Fields borrowed from SC.Copyable:
- isCopyable
- Fields borrowed from SC.Error:
- code, label, message
Class Methods
- clamp(value, min, max)
- clampInt(value, min, max)
- clampToDeviceGamut(value)
- from(color)
- hslToRgb(h, s, l)
- hsvToRgb(h, s, v)
- rgbToHsl(r, g, b)
- rgbToHsv(r, g, b)
Instance Methods
- a(key, value)
- add(color)
- b(key, value)
- copy()
- g(key, value)
- isEqualTo(color)
- mult(multipler)
- r(key, value)
- reset()
- sub(color)
- toArgb()
- toHex()
- toHsl()
- toHsla()
- toRgb()
- toRgba()
Field Detail
cssText StringThe CSS string representation that will be best displayed by the browser.
In the case of an invalid color, this contains the invalid string that was used to create or update it.
- Default value:
- null
- See:
- SC.Error
The current hue of this color. Hue is a float in degrees between 0° and 360°.
Whether the color is valid. Attempting to set cssText
or call from
with invalid input
will put the color into an error state until updated with a valid string or reset.
- Default value:
- NO
- See:
- SC.Error
A mapping of anglicized colors to their hexadecimal representation.
Computed by running the following code at http://www.w3.org/TR/css3-color
var T = {}, color = null, colors = document.querySelectorAll('.colortable')[1].querySelectorAll('.c');
for (var i = 0; i < colors.length; i++) {
if (i % 4 === 0) {
color = colors[i].getAttribute('style').split(':')[1];
} else if (i % 4 === 1) {
T[color] = colors[i].getAttribute('style').split(':')[1].toUpperCase();
}
}
JSON.stringify(T)
;
- See:
- http://www.w3.org/TR/css3-color/#svg-color
The current lightness of this color. Saturation is a percent between 0 and 1.
The original color string from which this object was created.
For example, if your color was created via SC.Color.from("burlywood")
,
then this would be set to "burlywood"
.
- Default value:
- null
The current saturation of this color. Saturation is a percent between 0 and 1.
Whether this browser supports the rgba color model. Check courtesy of Modernizr.
- See:
- https://github.com/Modernizr/Modernizr/blob/master/modernizr.js#L552
A read-only property which always returns a valid CSS property. If the color is in an error state, it returns 'transparent'.
Class Method Detail
Used to clamp a value in between a minimum value and a maximum value.
- Parameters:
- value Number
- The value to clamp.
- min Number
- The minimum number the value can be.
- max Number
- The maximum number the value can be.
- Returns:
- Number
- The value clamped between min and max.
- Parameters:
- value Number
- The value to clamp.
- min Number
- The minimum number the value can be.
- max Number
- The maximum number the value can be.
- Returns:
- Number
- The value clamped between min and max as an integer.
- See:
- SC.Color.clamp
Clamps a number so it lies in the device gamut. For screens, this an integer between 0 and 255.
- Parameters:
- value Number
- The value to clamp
- Returns:
- Number
- The value clamped to the device gamut.
Parses any valid CSS color into a SC.Color
object. Given invalid input, will return a
SC.Color
object in an error state (with isError
: YES).
Returns the RGB for a color defined in the HSL color space.
(Notes are taken from the W3 spec, and are written in ABC)
- Parameters:
- h Number
- The hue of the color as a degree between 0° and 360°
- s Number
- The saturation of the color as a percent between 0 and 1.
- l Number
- The luminosity of the color as a percent between 0 and 1.
- Returns:
- Number[]
A RGB triple in the form
(r, g, b)
where each of the values are integers between 0 and 255.
- See:
- http://www.w3.org/TR/css3-color/#hsl-color
Returns the RGB for a color defined in the HSV color space.
- Parameters:
- h Number
- The hue of the color as a degree between 0° and 360°
- s Number
- The saturation of the color as a percent between 0 and 1.
- v Number
- The value of the color as a percent between 0 and 1.
- Returns:
- Number[]
A RGB triple in the form
(r, g, b)
where each of the values are integers between 0 and 255.
Returns an RGB color transformed into the
HSL colorspace as triple (h, s, l)
.
- Parameters:
- r Number
- The red component as an integer between 0 and 255.
- g Number
- The green component as an integer between 0 and 255.
- b Number
- The blue component as an integer between 0 and 255.
- Returns:
- Number[]
A HSL triple in the form
(h, s, l)
whereh
is in degrees (as a float) between 0° and 360° ands
andl
are percents between 0 and 1.
Returns an RGB color transformed into the
HSV colorspace as triple (h, s, v)
.
- Parameters:
- r Number
- The red component as an integer between 0 and 255.
- g Number
- The green component as an integer between 0 and 255.
- b Number
- The blue component as an integer between 0 and 255.
- Returns:
- Number[]
A HSV triple in the form
(h, s, v)
whereh
is in degrees (as a float) between 0° and 360° ands
andv
are percents between 0 and 1.
Instance Method Detail
The alpha channel (opacity).
a
is a decimal value between 0 and 1.
- Parameters:
- key
- value
Returns a new color that's the addition of two colors.
Note that the resulting a, r, g and b values are not clamped to within valid ranges.
The blue value.
b
is an integer between 0 and 255.
- Parameters:
- key
- value
Returns a clone of this color. This will always a deep clone.
- Returns:
- SC.Color
- The clone color.
The green value.
g
is an integer between 0 and 255.
- Parameters:
- key
- value
Returns a color that has it's units uniformly multiplied by a given multiplier.
Note that the result might not be a valid CSS color.
- Parameters:
- multipler Number
- How much to multiply rgba by.
- Returns:
- SC.Color
- The adjusted color.
The red value.
r
is an integer between 0 and 255.
- Parameters:
- key
- value
Resets an errored color to its last valid color. If the color has never been valid, it resets to black.
- Returns:
- SC.Color
- receiver
Returns a color that's the difference between two colors.
Note that the result might not be a valid CSS color.
Returns a CSS string of the color under the #aarrggbb scheme.
This color is only valid for IE filters. This is here as a hack to support animating rgba values in older versions of IE by using filter gradients with no change in the actual gradient.
- Returns:
- String
- The color in the rgba color space as an argb value.
Returns a CSS string of the color under the #rrggbb scheme.
- Returns:
- String
- The color in the rgb color space as a hex value.
Returns a CSS string of the color under the hsl() scheme.
- Returns:
- String
- The color in the hsl color space.
Returns a CSS string of the color under the hsla() scheme.
- Returns:
- String
- The color in the hsla color space.
Returns a CSS string of the color under the rgb() scheme.
- Returns:
- String
- The color in the rgb color space.
Returns a CSS string of the color under the rgba() scheme.
- Returns:
- String
- The color in the rgba color space.