platform.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. export var DEFAULT_FONT_SIZE = 12;
  2. export var DEFAULT_FONT_FAMILY = 'sans-serif';
  3. export var DEFAULT_FONT = DEFAULT_FONT_SIZE + "px " + DEFAULT_FONT_FAMILY;
  4. var OFFSET = 20;
  5. var SCALE = 100;
  6. var defaultWidthMapStr = "007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";
  7. function getTextWidthMap(mapStr) {
  8. var map = {};
  9. if (typeof JSON === 'undefined') {
  10. return map;
  11. }
  12. for (var i = 0; i < mapStr.length; i++) {
  13. var char = String.fromCharCode(i + 32);
  14. var size = (mapStr.charCodeAt(i) - OFFSET) / SCALE;
  15. map[char] = size;
  16. }
  17. return map;
  18. }
  19. export var DEFAULT_TEXT_WIDTH_MAP = getTextWidthMap(defaultWidthMapStr);
  20. export var platformApi = {
  21. createCanvas: function () {
  22. return typeof document !== 'undefined'
  23. && document.createElement('canvas');
  24. },
  25. measureText: (function () {
  26. var _ctx;
  27. var _cachedFont;
  28. return function (text, font) {
  29. if (!_ctx) {
  30. var canvas = platformApi.createCanvas();
  31. _ctx = canvas && canvas.getContext('2d');
  32. }
  33. if (_ctx) {
  34. if (_cachedFont !== font) {
  35. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  36. }
  37. return _ctx.measureText(text);
  38. }
  39. else {
  40. text = text || '';
  41. font = font || DEFAULT_FONT;
  42. var res = /(\d+)px/.exec(font);
  43. var fontSize = res && +res[1] || DEFAULT_FONT_SIZE;
  44. var width = 0;
  45. if (font.indexOf('mono') >= 0) {
  46. width = fontSize * text.length;
  47. }
  48. else {
  49. for (var i = 0; i < text.length; i++) {
  50. var preCalcWidth = DEFAULT_TEXT_WIDTH_MAP[text[i]];
  51. width += preCalcWidth == null ? fontSize : (preCalcWidth * fontSize);
  52. }
  53. }
  54. return { width: width };
  55. }
  56. };
  57. })(),
  58. loadImage: function (src, onload, onerror) {
  59. var image = new Image();
  60. image.onload = onload;
  61. image.onerror = onerror;
  62. image.src = src;
  63. return image;
  64. }
  65. };
  66. export function setPlatformAPI(newPlatformApis) {
  67. for (var key in platformApi) {
  68. if (newPlatformApis[key]) {
  69. platformApi[key] = newPlatformApis[key];
  70. }
  71. }
  72. }