1+ // ******************************
2+ // A Bit More Practice with Classes ******************************
3+
4+ console . log ( 'A Bit More Practice with Classes' )
5+ console . log ( '\n' )
6+
7+ // Example 1
8+
9+ class Color {
10+ constructor ( r , g , b ) {
11+ this . r = r
12+ this . g = g
13+ this . b = b
14+ // Calling a function automatically whenever you make a new color
15+ this . calcHSL ( )
16+ }
17+ hsl ( ) {
18+ const { h, s, l} = this
19+ return `hsl(${ h } , ${ s } %, ${ l } %)`
20+ }
21+ opposite ( ) {
22+ const { h, s, l } = this
23+ const newHue = ( h + 180 ) % 360
24+ return `hsl(${ newHue } , ${ s } %, ${ l } %)`
25+ }
26+ fullySaturated ( ) {
27+ const { h, l} = this
28+ return `hsl(${ h } , 100%, ${ l } %)`
29+
30+ }
31+ calcHSL ( ) {
32+ let { r, g, b} = this
33+ // Make r, g, and b fractions of 1
34+ r /= 255
35+ g /= 255
36+ b /= 255
37+
38+ // Find greatest and smallest channel values
39+ let cmin = Math . min ( r , g , b ) ,
40+ cmax = Math . max ( r , g , b ) ,
41+ delta = cmax - cmin ,
42+ h = 0 ,
43+ s = 0 ,
44+ l = 0
45+ if ( delta == 0 ) h = 0
46+ else if ( cmax == r )
47+ // Red is max
48+ h = ( ( g - b ) / delta ) % 6
49+ else if ( cmax == g )
50+ // Green is max
51+ h = ( b - r ) / delta + 2
52+ // Blue is max
53+ else h = ( r - g ) / delta + 4
54+
55+ h = Math . round ( h * 60 )
56+
57+ // Make negative hues positive behind 360°
58+ if ( h < 0 ) h += 360
59+ // Calculate lightness
60+ l = ( cmax + cmin ) / 2
61+
62+ // Calculate saturation
63+ s = delta == 0 ? 0 : delta / ( 1 - Math . abs ( 2 * l - 1 ) )
64+
65+ // Multiply l and s by 100
66+ s = + ( s * 100 ) . toFixed ( 1 )
67+ l = + ( l * 100 ) . toFixed ( 1 )
68+ this . h = h
69+ this . s = s
70+ this . l = l
71+ }
72+ }
73+
74+ const red = new Color ( 255 , 67 , 89 , 'tomato' )
75+ const white = new Color ( 255 , 255 , 255 , 'white' )
76+ white . calcHSL ( )
77+ console . log ( white ) ;
78+ console . log ( white . hsl ( ) ) ;
79+
80+ console . log ( '\n' )
81+ red . hsl ( )
82+ document . body . style . backgroundColor = red . hsl ( )
83+ // document.body.style.backgroundColor = red.opposite()
84+
85+ const orange = new Color ( 230 , 128 , 34 , 'orange' )
86+ document . body . style . backgroundColor = orange . hsl ( )
87+ // document.body.style.backgroundColor = orange.fullySaturated()
0 commit comments