Advertisement
Guest User

Untitled

a guest
Feb 14th, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head lang="en">
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8.  
  9. <script>
  10. var getTextWidthDOM = function(text, fontStyle) {
  11. var node = getTextWidthDOM.node,
  12. width;
  13.  
  14. if ( ! node) {
  15. node = getTextWidthDOM.node = document.createElement('span');
  16.  
  17. node.style.whiteSpace = 'nowrap';
  18. node.style.visibility = 'hidden';
  19. node.style.position = 'absolute';
  20. node.style.height = 'auto';
  21. node.style.width = 'auto';
  22. }
  23.  
  24. document.body.appendChild(node);
  25.  
  26. node.style.font = fontStyle;
  27. node.innerHTML = text;
  28. width = node.offsetWidth;
  29.  
  30. document.body.removeChild(node);
  31.  
  32. return width;
  33. };
  34.  
  35. var getTextWidthCanvas = function(text, fontStyle) {
  36. getTextWidthCanvas.canvas || (getTextWidthCanvas.canvas = document.createElement("canvas"));
  37.  
  38. var context = getTextWidthCanvas.canvas.getContext("2d");
  39.  
  40. context.font = fontStyle;
  41.  
  42. return context.measureText(text).width;
  43. };
  44.  
  45.  
  46. var CHARS_RANGES = [
  47. [ 0x0400, 0x04FF ], // Cyrillic
  48. [ 0x001F, 0x007F ] // Latin
  49. ],
  50. FONT_STYLE = '13px arial',
  51. charsWidth = {};
  52.  
  53. CHARS_RANGES.forEach(function(range) {
  54. for (var charCode = range[0], char; charCode <= range[1]; charCode++) {
  55. char = String.fromCharCode(charCode);
  56.  
  57. charsWidth[char] = [
  58. getTextWidthCanvas(char, FONT_STYLE),
  59. getTextWidthDOM(char, FONT_STYLE)
  60. ];
  61. }
  62. });
  63.  
  64. console.log(charsWidth);
  65.  
  66. </script>
  67. </body>
  68. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement