@@ -29,6 +29,76 @@ CanvasKit.getColorComponents = function(color) {
2929 ]
3030}
3131
32+ // parseColorString takes in a CSS color value and returns a CanvasKit.Color
33+ // (which is just a 32 bit integer, 8 bits per channel). An optional colorMap
34+ // may be provided which maps custom strings to values (e.g. {'springgreen':4278255487}).
35+ // In the CanvasKit canvas2d shim layer, we provide this map for processing
36+ // canvas2d calls, but not here for code size reasons.
37+ CanvasKit . parseColorString = function ( colorStr , colorMap ) {
38+ colorStr = colorStr . toLowerCase ( ) ;
39+ // See https://drafts.csswg.org/css-color/#typedef-hex-color
40+ if ( colorStr . startsWith ( '#' ) ) {
41+ var r , g , b , a = 255 ;
42+ switch ( colorStr . length ) {
43+ case 9 : // 8 hex chars #RRGGBBAA
44+ a = parseInt ( colorStr . slice ( 7 , 9 ) , 16 ) ;
45+ case 7 : // 6 hex chars #RRGGBB
46+ r = parseInt ( colorStr . slice ( 1 , 3 ) , 16 ) ;
47+ g = parseInt ( colorStr . slice ( 3 , 5 ) , 16 ) ;
48+ b = parseInt ( colorStr . slice ( 5 , 7 ) , 16 ) ;
49+ break ;
50+ case 5 : // 4 hex chars #RGBA
51+ // multiplying by 17 is the same effect as
52+ // appending another character of the same value
53+ // e.g. e => ee == 14 => 238
54+ a = parseInt ( colorStr . slice ( 4 , 5 ) , 16 ) * 17 ;
55+ case 4 : // 6 hex chars #RGB
56+ r = parseInt ( colorStr . slice ( 1 , 2 ) , 16 ) * 17 ;
57+ g = parseInt ( colorStr . slice ( 2 , 3 ) , 16 ) * 17 ;
58+ b = parseInt ( colorStr . slice ( 3 , 4 ) , 16 ) * 17 ;
59+ break ;
60+ }
61+ return CanvasKit . Color ( r , g , b , a / 255 ) ;
62+
63+ } else if ( colorStr . startsWith ( 'rgba' ) ) {
64+ // Trim off rgba( and the closing )
65+ colorStr = colorStr . slice ( 5 , - 1 ) ;
66+ var nums = colorStr . split ( ',' ) ;
67+ return CanvasKit . Color ( + nums [ 0 ] , + nums [ 1 ] , + nums [ 2 ] ,
68+ valueOrPercent ( nums [ 3 ] ) ) ;
69+ } else if ( colorStr . startsWith ( 'rgb' ) ) {
70+ // Trim off rgba( and the closing )
71+ colorStr = colorStr . slice ( 4 , - 1 ) ;
72+ var nums = colorStr . split ( ',' ) ;
73+ // rgb can take 3 or 4 arguments
74+ return CanvasKit . Color ( + nums [ 0 ] , + nums [ 1 ] , + nums [ 2 ] ,
75+ valueOrPercent ( nums [ 3 ] ) ) ;
76+ } else if ( colorStr . startsWith ( 'gray(' ) ) {
77+ // TODO
78+ } else if ( colorStr . startsWith ( 'hsl' ) ) {
79+ // TODO
80+ } else if ( colorMap ) {
81+ // Try for named color
82+ var nc = colorMap [ colorStr ] ;
83+ if ( nc !== undefined ) {
84+ return nc ;
85+ }
86+ }
87+ SkDebug ( 'unrecognized color ' + colorStr ) ;
88+ return CanvasKit . BLACK ;
89+ }
90+
91+ function valueOrPercent ( aStr ) {
92+ if ( aStr === undefined ) {
93+ return 1 ; // default to opaque.
94+ }
95+ var a = parseFloat ( aStr ) ;
96+ if ( aStr && aStr . indexOf ( '%' ) !== - 1 ) {
97+ return a / 100 ;
98+ }
99+ return a ;
100+ }
101+
32102CanvasKit . multiplyByAlpha = function ( color , alpha ) {
33103 if ( alpha === 1 ) {
34104 return color ;
0 commit comments