measureText.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /*
  2. This library rewrites the Canvas2D "measureText" function
  3. so that it returns a more complete metrics object.
  4. ** -----------------------------------------------------------------------------
  5. CHANGELOG:
  6. 2012-01-21 - Whitespace handling added by Joe Turner
  7. (https://github.com/oampo)
  8. ** -----------------------------------------------------------------------------
  9. */
  10. /**
  11. @license
  12. fontmetrics.js - https://github.com/Pomax/fontmetrics.js
  13. Copyright (C) 2011 by Mike "Pomax" Kamermans
  14. Permission is hereby granted, free of charge, to any person obtaining a copy
  15. of this software and associated documentation files (the "Software"), to deal
  16. in the Software without restriction, including without limitation the rights
  17. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18. copies of the Software, and to permit persons to whom the Software is
  19. furnished to do so, subject to the following conditions:
  20. The above copyright notice and this permission notice shall be included in
  21. all copies or substantial portions of the Software.
  22. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  23. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  24. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  25. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  26. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  27. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  28. THE SOFTWARE.
  29. **/
  30. /*global define*/
  31. define(function() {
  32. /*jshint strict:false*/
  33. /*
  34. var NAME = "FontMetrics Library"
  35. var VERSION = "1-2012.0121.1300";
  36. // if there is no getComputedStyle, this library won't work.
  37. if(!document.defaultView.getComputedStyle) {
  38. throw("ERROR: 'document.defaultView.getComputedStyle' not found. This library only works in browsers that can report computed CSS values.");
  39. }
  40. // store the old text metrics function on the Canvas2D prototype
  41. CanvasRenderingContext2D.prototype.measureTextWidth = CanvasRenderingContext2D.prototype.measureText;
  42. */
  43. /**
  44. * shortcut function for getting computed CSS values
  45. */
  46. var getCSSValue = function(element, property) {
  47. return document.defaultView.getComputedStyle(element,null).getPropertyValue(property);
  48. };
  49. /*
  50. // debug function
  51. var show = function(canvas, ctx, xstart, w, h, metrics)
  52. {
  53. document.body.appendChild(canvas);
  54. ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
  55. ctx.beginPath();
  56. ctx.moveTo(xstart,0);
  57. ctx.lineTo(xstart,h);
  58. ctx.closePath();
  59. ctx.stroke();
  60. ctx.beginPath();
  61. ctx.moveTo(xstart+metrics.bounds.maxx,0);
  62. ctx.lineTo(xstart+metrics.bounds.maxx,h);
  63. ctx.closePath();
  64. ctx.stroke();
  65. ctx.beginPath();
  66. ctx.moveTo(0,h/2-metrics.ascent);
  67. ctx.lineTo(w,h/2-metrics.ascent);
  68. ctx.closePath();
  69. ctx.stroke();
  70. ctx.beginPath();
  71. ctx.moveTo(0,h/2+metrics.descent);
  72. ctx.lineTo(w,h/2+metrics.descent);
  73. ctx.closePath();
  74. ctx.stroke();
  75. }
  76. */
  77. /**
  78. * The new text metrics function
  79. */
  80. var measureText = function(context2D, textstring, stroke, fill) {
  81. var metrics = context2D.measureText(textstring),
  82. fontFamily = getCSSValue(context2D.canvas,"font-family"),
  83. fontSize = getCSSValue(context2D.canvas,"font-size").replace("px",""),
  84. isSpace = !(/\S/.test(textstring));
  85. metrics.fontsize = fontSize;
  86. // for text lead values, we meaure a multiline text container.
  87. var leadDiv = document.createElement("div");
  88. leadDiv.style.position = "absolute";
  89. leadDiv.style.opacity = 0;
  90. leadDiv.style.font = fontSize + "px " + fontFamily;
  91. leadDiv.innerHTML = textstring + "<br/>" + textstring;
  92. document.body.appendChild(leadDiv);
  93. // make some initial guess at the text leading (using the standard TeX ratio)
  94. metrics.leading = 1.2 * fontSize;
  95. // then we try to get the real value from the browser
  96. var leadDivHeight = getCSSValue(leadDiv,"height");
  97. leadDivHeight = leadDivHeight.replace("px","");
  98. if (leadDivHeight >= fontSize * 2) { metrics.leading = (leadDivHeight/2) | 0; }
  99. document.body.removeChild(leadDiv);
  100. // if we're not dealing with white space, we can compute metrics
  101. if (!isSpace) {
  102. // Have characters, so measure the text
  103. var canvas = document.createElement("canvas");
  104. var padding = 100;
  105. canvas.width = metrics.width + padding;
  106. canvas.height = 3*fontSize;
  107. canvas.style.opacity = 1;
  108. canvas.style.fontFamily = fontFamily;
  109. canvas.style.fontSize = fontSize;
  110. var ctx = canvas.getContext("2d");
  111. ctx.font = fontSize + "px " + fontFamily;
  112. var w = canvas.width,
  113. h = canvas.height,
  114. baseline = h/2;
  115. // Set all canvas pixeldata values to 255, with all the content
  116. // data being 0. This lets us scan for data[i] != 255.
  117. ctx.fillStyle = "white";
  118. ctx.fillRect(-1, -1, w + 2, h + 2);
  119. if (stroke) {
  120. ctx.strokeStyle = "black";
  121. ctx.lineWidth = context2D.lineWidth;
  122. ctx.strokeText(textstring, (padding / 2), baseline);
  123. }
  124. if (fill) {
  125. ctx.fillStyle = "black";
  126. ctx.fillText(textstring, padding / 2, baseline);
  127. }
  128. var pixelData = ctx.getImageData(0, 0, w, h).data;
  129. // canvas pixel data is w*4 by h*4, because R, G, B and A are separate,
  130. // consecutive values in the array, rather than stored as 32 bit ints.
  131. var i = 0,
  132. w4 = w * 4,
  133. len = pixelData.length;
  134. // Finding the ascent uses a normal, forward scanline
  135. while (++i < len && pixelData[i] === 255) {}
  136. var ascent = (i/w4)|0;
  137. // Finding the descent uses a reverse scanline
  138. i = len - 1;
  139. while (--i > 0 && pixelData[i] === 255) {}
  140. var descent = (i/w4)|0;
  141. // find the min-x coordinate
  142. for(i = 0; i<len && pixelData[i] === 255; ) {
  143. i += w4;
  144. if(i>=len) { i = (i-len) + 4; }}
  145. var minx = ((i%w4)/4) | 0;
  146. // find the max-x coordinate
  147. var step = 1;
  148. for(i = len-3; i>=0 && pixelData[i] === 255; ) {
  149. i -= w4;
  150. if(i<0) { i = (len - 3) - (step++)*4; }}
  151. var maxx = ((i%w4)/4) + 1 | 0;
  152. // set font metrics
  153. metrics.ascent = (baseline - ascent);
  154. metrics.descent = (descent - baseline);
  155. metrics.bounds = { minx: minx - (padding/2),
  156. maxx: maxx - (padding/2),
  157. miny: 0,
  158. maxy: descent-ascent };
  159. metrics.height = 1+(descent - ascent);
  160. }
  161. // if we ARE dealing with whitespace, most values will just be zero.
  162. else {
  163. // Only whitespace, so we can't measure the text
  164. metrics.ascent = 0;
  165. metrics.descent = 0;
  166. metrics.bounds = { minx: 0,
  167. maxx: metrics.width, // Best guess
  168. miny: 0,
  169. maxy: 0 };
  170. metrics.height = 0;
  171. }
  172. return metrics;
  173. };
  174. return measureText;
  175. });