Color.js 1.9 KB
Newer Older
M
Mr.doob 已提交
1 2 3 4
/**
 * @author mr.doob / http://mrdoob.com/
 */

5
THREE.Color = function ( hex ) {
M
Mr.doob 已提交
6

M
Mr.doob 已提交
7 8
	this.setHex( hex );

9
};
M
Mr.doob 已提交
10

P
philogb 已提交
11 12
THREE.Color.prototype = {

13 14
	autoUpdate: true,

15
	setRGB: function ( r, g, b ) {
M
Mr.doob 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29

		this.r = r;
		this.g = g;
		this.b = b;

		if ( this.autoUpdate ) {

			this.updateHex();
			this.updateStyleString();

		}

	},

30 31
	setHSV: function ( h, s, v ) {

32 33 34
		// based on MochiKit implementation by Bob Ippolito
		// h,s,v ranges are < 0.0 - 1.0 >

35
		var red, green, blue, i, f, p, q, t;
36

37
		if ( v == 0.0 ) {
38

39
			red = green = blue = 0;
40

41
		} else {
42

43 44 45 46 47
			i = Math.floor( h * 6 );
			f = ( h * 6 ) - i;
			p = v * ( 1 - s );
			q = v * ( 1 - ( s * f ) );
			t = v * ( 1 - ( s * ( 1 - f ) ) );
48

49
			switch ( i ) {
50

51 52 53 54 55 56 57
				case 1: red = q; green = v; blue = p; break;
				case 2: red = p; green = v; blue = t; break;
				case 3: red = p; green = q; blue = v; break;
				case 4: red = t; green = p; blue = v; break;
				case 5: red = v; green = p; blue = q; break;
				case 6: // fall through
				case 0: red = v; green = t; blue = p; break;
58

59
			}
60

61
		}
62

63 64 65 66 67 68 69 70 71 72
		this.r = red;
		this.g = green;
		this.b = blue;

		if ( this.autoUpdate ) {

			this.updateHex();
			this.updateStyleString();

		}
73

74
	},
75

M
Mr.doob 已提交
76
	setHex: function ( hex ) {
M
Mr.doob 已提交
77

78
		this.hex = ( ~~ hex ) & 0xffffff;
M
Mr.doob 已提交
79 80 81 82 83 84 85

		if ( this.autoUpdate ) {

			this.updateRGBA();
			this.updateStyleString();

		}
M
Mr.doob 已提交
86

P
philogb 已提交
87
	},
M
Mr.doob 已提交
88

P
philogb 已提交
89
	updateHex: function () {
M
Mr.doob 已提交
90

91
		this.hex = ~~( this.r * 255 ) << 16 ^ ~~( this.g * 255 ) << 8 ^ ~~( this.b * 255 );
M
Mr.doob 已提交
92

P
philogb 已提交
93
	},
M
Mr.doob 已提交
94

P
philogb 已提交
95
	updateRGBA: function () {
M
Mr.doob 已提交
96

M
Mr.doob 已提交
97 98 99
		this.r = ( this.hex >> 16 & 255 ) / 255;
		this.g = ( this.hex >> 8 & 255 ) / 255;
		this.b = ( this.hex & 255 ) / 255;
M
Mr.doob 已提交
100

P
philogb 已提交
101
	},
M
Mr.doob 已提交
102

P
philogb 已提交
103
	updateStyleString: function () {
M
Mr.doob 已提交
104

105
		this.__styleString = 'rgb(' + ~~( this.r * 255 ) + ',' + ~~( this.g * 255 ) + ',' + ~~( this.b * 255 ) + ')';
M
Mr.doob 已提交
106

P
philogb 已提交
107
	},
M
Mr.doob 已提交
108

109 110 111 112 113 114
	clone: function () {

		return new THREE.Color( this.hex );

	},

P
philogb 已提交
115
	toString: function () {
M
Mr.doob 已提交
116

117
		return 'THREE.Color ( r: ' + this.r + ', g: ' + this.g + ', b: ' + this.b + ', hex: ' + this.hex + ' )';
M
Mr.doob 已提交
118

P
philogb 已提交
119
	}
M
Mr.doob 已提交
120

M
Mr.doob 已提交
121
};