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

Class Methods

Instance Methods

Field Detail

cssText String

The CSS string representation that will be best displayed by the browser.

errorValue String

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
hue Number

The current hue of this color. Hue is a float in degrees between 0° and 360°.

isError Boolean

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
SC.Color.KEYWORDS

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
luminosity Number

The current lightness of this color. Saturation is a percent between 0 and 1.

original String

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
saturation Number

The current saturation of this color. Saturation is a percent between 0 and 1.

SC.Color.supportsArgb Boolean
Whether this browser supports the argb color model.
SC.Color.supportsRgba Boolean

Whether this browser supports the rgba color model. Check courtesy of Modernizr.

See:
https://github.com/Modernizr/Modernizr/blob/master/modernizr.js#L552
validCssText String

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

clamp(value, min, max)

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.
clampInt(value, min, max)
Clamps a number, then rounds it to the nearest integer.
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
clampToDeviceGamut(value)

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.
from(color)

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).

Parameters:
color String
The CSS color value to parse.
Returns:
SC.Color
The color object representing the color passed in.
hslToRgb(h, s, l)

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
hsvToRgb(h, s, v)

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.

rgbToHsl(r, g, b)

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) where h is in degrees (as a float) between 0° and 360° and s and l are percents between 0 and 1.

rgbToHsv(r, g, b)

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) where h is in degrees (as a float) between 0° and 360° and s and v are percents between 0 and 1.

Instance Method Detail

a(key, value)

The alpha channel (opacity). a is a decimal value between 0 and 1.

Parameters:
key
value
add(color)

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.

Parameters:
color SC.Color
The color to add to this one.
Returns:
SC.Color
The addition of the two colors.
b(key, value)

The blue value. b is an integer between 0 and 255.

Parameters:
key
value
copy()

Returns a clone of this color. This will always a deep clone.

Returns:
SC.Color
The clone color.
g(key, value)

The green value. g is an integer between 0 and 255.

Parameters:
key
value
isEqualTo(color)
Whether two colors are equivalent.
Parameters:
color SC.Color
The color to compare this one to.
Returns:
Boolean
YES if the two colors are equivalent
mult(multipler)

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.
r(key, value)

The red value. r is an integer between 0 and 255.

Parameters:
key
value
reset()

Resets an errored color to its last valid color. If the color has never been valid, it resets to black.

Returns:
SC.Color
receiver
sub(color)

Returns a color that's the difference between two colors.

Note that the result might not be a valid CSS color.

Parameters:
color SC.Color
The color to subtract from this one.
Returns:
SC.Color
The difference between the two colors.
toArgb()

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.
toHex()

Returns a CSS string of the color under the #rrggbb scheme.

Returns:
String
The color in the rgb color space as a hex value.
toHsl()

Returns a CSS string of the color under the hsl() scheme.

Returns:
String
The color in the hsl color space.
toHsla()

Returns a CSS string of the color under the hsla() scheme.

Returns:
String
The color in the hsla color space.
toRgb()

Returns a CSS string of the color under the rgb() scheme.

Returns:
String
The color in the rgb color space.
toRgba()

Returns a CSS string of the color under the rgba() scheme.

Returns:
String
The color in the rgba color space.
Documentation generated by JsDoc Toolkit 2.4.0 on Wed Apr 08 2015 10:02:20 GMT-0600 (CST)