blob: 549208dba8ed180b6f0d2bfbd7b0233bf2a9d720 [file] [log] [blame]
Kevin Lubick53eabf62018-12-10 12:41:26 -05001// Functions dealing with parsing/stringifying fonts go here.
2
3var units = 'px|pt|pc|in|cm|mm|%|em|ex|ch|rem|q';
4var fontSizeRegex = new RegExp('([\\d\\.]+)(' + units + ')');
Kevin Lubickddd0a332018-12-12 10:35:13 -05005var defaultHeight = 16;
Kevin Lubick53eabf62018-12-10 12:41:26 -05006// Based off of node-canvas's parseFont
Kevin Lubickddd0a332018-12-12 10:35:13 -05007// returns font size in px, which represents the em width.
Kevin Lubick53eabf62018-12-10 12:41:26 -05008function parseFontSize(fontStr) {
9 // This is naive and doesn't account for line-height yet
10 // (but neither does node-canvas's?)
11 var fontSize = fontSizeRegex.exec(fontStr);
12 if (!fontSize) {
13 SkDebug('Could not parse font size' + fontStr);
14 return 16;
15 }
16 var size = parseFloat(fontSize[1]);
17 var unit = fontSize[2];
18 switch (unit) {
19 case 'pt':
Kevin Lubick53eabf62018-12-10 12:41:26 -050020 case 'em':
21 case 'rem':
Kevin Lubickddd0a332018-12-12 10:35:13 -050022 return size * 4/3;
23 case 'px':
24 return size;
25 case 'pc':
26 return size * 16;
27 case 'in':
28 return size * 96;
29 case 'cm':
30 return size * 96.0 / 2.54;
31 case 'mm':
32 return size * (96.0 / 25.4);
33 case 'q': // quarter millimeters
34 return size * (96.0 / 25.4 / 4);
35 case '%':
36 return size * (defaultHeight / 75);
Kevin Lubick53eabf62018-12-10 12:41:26 -050037 }
38}