1 /* Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
7 base
.exportTo('base', function() {
8 function Color(opt_r
, opt_g
, opt_b
, opt_a
) {
9 this.r
= Math
.floor(opt_r
) || 0;
10 this.g
= Math
.floor(opt_g
) || 0;
11 this.b
= Math
.floor(opt_b
) || 0;
15 Color
.fromString = function(str
) {
18 if (str
.substr(0, 4) == 'rgb(') {
19 tmp
= str
.substr(4, str
.length
- 5);
20 values
= tmp
.split(',').map(function(v
) {
21 return v
.replace(/^\s+/, '', 'g');
23 if (values
.length
!= 3)
24 throw new Error('Malformatted rgb-expression');
29 } else if (str
.substr(0, 4) == 'rgba(') {
30 tmp
= str
.substr(5, str
.length
- 6);
31 values
= tmp
.split(',').map(function(v
) {
32 return v
.replace(/^\s+/, '', 'g');
34 if (values
.length
!= 3)
35 throw new Error('Malformatted rgb-expression');
40 parseFloat(values
[3]));
41 } else if (str
[0] == '#' && str
.length
== 7) {
43 parseInt(str
.substr(1, 2), 16),
44 parseInt(str
.substr(3, 2), 16),
45 parseInt(str
.substr(5, 2), 16));
47 throw new Error('Unrecognized string format.');
51 Color
.lerp = function(a
, b
, percent
) {
52 if (a
.a
!== undefined && b
.a
!== undefined)
53 return Color
.lerpRGBA(a
, b
, percent
);
54 return Color
.lerpRGB(a
, b
, percent
);
56 Color
.lerpRGB = function(a
, b
, percent
) {
58 ((b
.r
- a
.r
) * percent
) + a
.r
,
59 ((b
.g
- a
.g
) * percent
) + a
.g
,
60 ((b
.b
- a
.b
) * percent
) + a
.b
);
63 Color
.lerpRGBA = function(a
, b
, percent
) {
65 ((b
.r
- a
.r
) * percent
) + a
.r
,
66 ((b
.g
- a
.g
) * percent
) + a
.g
,
67 ((b
.b
- a
.b
) * percent
) + a
.b
,
68 ((b
.a
- a
.a
) * percent
) + a
.a
);
72 brighten: function(opt_k
) {
77 Math
.min(255, this.r
+ Math
.floor(this.r
* k
)),
78 Math
.min(255, this.g
+ Math
.floor(this.g
* k
)),
79 Math
.min(255, this.b
+ Math
.floor(this.b
* k
)));
82 toString: function() {
83 if (this.a
!== undefined) {
85 this.r
+ ',' + this.g
+ ',' +
86 this.b
+ ',' + this.a
+ ')';
88 return 'rgb(' + this.r
+ ',' + this.g
+ ',' + this.b
+ ')';