units.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /**
  2. * Package: svgedit.units
  3. *
  4. * Licensed under the Apache License, Version 2
  5. *
  6. * Copyright(c) 2010 Alexis Deveria
  7. * Copyright(c) 2010 Jeff Schiller
  8. */
  9. // Dependencies:
  10. // 1) jQuery
  11. var svgedit = svgedit || {};
  12. (function() {
  13. if (!svgedit.units) {
  14. svgedit.units = {};
  15. }
  16. var w_attrs = ['x', 'x1', 'cx', 'rx', 'width'];
  17. var h_attrs = ['y', 'y1', 'cy', 'ry', 'height'];
  18. var unit_attrs = $.merge(['r','radius'], w_attrs);
  19. var unitNumMap = {
  20. '%': 2,
  21. 'em': 3,
  22. 'ex': 4,
  23. 'px': 5,
  24. 'cm': 6,
  25. 'mm': 7,
  26. 'in': 8,
  27. 'pt': 9,
  28. 'pc': 10
  29. };
  30. $.merge(unit_attrs, h_attrs);
  31. // Container of elements.
  32. var elementContainer_;
  33. /**
  34. * Stores mapping of unit type to user coordinates.
  35. */
  36. var typeMap_ = {px: 1};
  37. /**
  38. * ElementContainer interface
  39. *
  40. * function getBaseUnit() - returns a string of the base unit type of the container ("em")
  41. * function getElement() - returns an element in the container given an id
  42. * function getHeight() - returns the container's height
  43. * function getWidth() - returns the container's width
  44. * function getRoundDigits() - returns the number of digits number should be rounded to
  45. */
  46. /**
  47. * Function: svgedit.units.init()
  48. * Initializes this module.
  49. *
  50. * Parameters:
  51. * elementContainer - an object implementing the ElementContainer interface.
  52. */
  53. svgedit.units.init = function(elementContainer) {
  54. elementContainer_ = elementContainer;
  55. var svgns = 'http://www.w3.org/2000/svg';
  56. // Get correct em/ex values by creating a temporary SVG.
  57. var svg = document.createElementNS(svgns, 'svg');
  58. document.body.appendChild(svg);
  59. var rect = document.createElementNS(svgns,'rect');
  60. rect.setAttribute('width',"1em");
  61. rect.setAttribute('height',"1ex");
  62. rect.setAttribute('x',"1in");
  63. svg.appendChild(rect);
  64. var bb = rect.getBBox();
  65. document.body.removeChild(svg);
  66. var inch = bb.x;
  67. typeMap_['em'] = bb.width;
  68. typeMap_['ex'] = bb.height;
  69. typeMap_['in'] = inch;
  70. typeMap_['cm'] = inch / 2.54;
  71. typeMap_['mm'] = inch / 25.4;
  72. typeMap_['pt'] = inch / 72;
  73. typeMap_['pc'] = inch / 6;
  74. typeMap_['%'] = 0;
  75. };
  76. // Group: Unit conversion functions
  77. // Function: svgedit.units.getTypeMap
  78. // Returns the unit object with values for each unit
  79. svgedit.units.getTypeMap = function() {
  80. return typeMap_;
  81. };
  82. // Function: svgedit.units.shortFloat
  83. // Rounds a given value to a float with number of digits defined in save_options
  84. //
  85. // Parameters:
  86. // val - The value as a String, Number or Array of two numbers to be rounded
  87. //
  88. // Returns:
  89. // If a string/number was given, returns a Float. If an array, return a string
  90. // with comma-seperated floats
  91. svgedit.units.shortFloat = function(val) {
  92. var digits = elementContainer_.getRoundDigits();
  93. if(!isNaN(val)) {
  94. // Note that + converts to Number
  95. return +((+val).toFixed(digits));
  96. } else if($.isArray(val)) {
  97. return svgedit.units.shortFloat(val[0]) + ',' + svgedit.units.shortFloat(val[1]);
  98. }
  99. return parseFloat(val).toFixed(digits) - 0;
  100. };
  101. // Function: svgedit.units.convertUnit
  102. // Converts the number to given unit or baseUnit
  103. svgedit.units.convertUnit = function(val, unit) {
  104. unit = unit || elementContainer_.getBaseUnit();
  105. // baseVal.convertToSpecifiedUnits(unitNumMap[unit]);
  106. // var val = baseVal.valueInSpecifiedUnits;
  107. // baseVal.convertToSpecifiedUnits(1);
  108. return svgedit.unit.shortFloat(val / typeMap_[unit]);
  109. };
  110. // Function: svgedit.units.setUnitAttr
  111. // Sets an element's attribute based on the unit in its current value.
  112. //
  113. // Parameters:
  114. // elem - DOM element to be changed
  115. // attr - String with the name of the attribute associated with the value
  116. // val - String with the attribute value to convert
  117. svgedit.units.setUnitAttr = function(elem, attr, val) {
  118. if(!isNaN(val)) {
  119. // New value is a number, so check currently used unit
  120. var old_val = elem.getAttribute(attr);
  121. // Enable this for alternate mode
  122. // if(old_val !== null && (isNaN(old_val) || elementContainer_.getBaseUnit() !== 'px')) {
  123. // // Old value was a number, so get unit, then convert
  124. // var unit;
  125. // if(old_val.substr(-1) === '%') {
  126. // var res = getResolution();
  127. // unit = '%';
  128. // val *= 100;
  129. // if(w_attrs.indexOf(attr) >= 0) {
  130. // val = val / res.w;
  131. // } else if(h_attrs.indexOf(attr) >= 0) {
  132. // val = val / res.h;
  133. // } else {
  134. // return val / Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2);
  135. // }
  136. // } else {
  137. // if(elementContainer_.getBaseUnit() !== 'px') {
  138. // unit = elementContainer_.getBaseUnit();
  139. // } else {
  140. // unit = old_val.substr(-2);
  141. // }
  142. // val = val / typeMap_[unit];
  143. // }
  144. //
  145. // val += unit;
  146. // }
  147. }
  148. elem.setAttribute(attr, val);
  149. };
  150. var attrsToConvert = {
  151. "line": ['x1', 'x2', 'y1', 'y2'],
  152. "circle": ['cx', 'cy', 'r'],
  153. "ellipse": ['cx', 'cy', 'rx', 'ry'],
  154. "foreignObject": ['x', 'y', 'width', 'height'],
  155. "rect": ['x', 'y', 'width', 'height'],
  156. "image": ['x', 'y', 'width', 'height'],
  157. "use": ['x', 'y', 'width', 'height'],
  158. "text": ['x', 'y']
  159. };
  160. // Function: svgedit.units.convertAttrs
  161. // Converts all applicable attributes to the configured baseUnit
  162. //
  163. // Parameters:
  164. // element - a DOM element whose attributes should be converted
  165. svgedit.units.convertAttrs = function(element) {
  166. var elName = element.tagName;
  167. var unit = elementContainer_.getBaseUnit();
  168. var attrs = attrsToConvert[elName];
  169. if(!attrs) return;
  170. var len = attrs.length
  171. for(var i = 0; i < len; i++) {
  172. var attr = attrs[i];
  173. var cur = element.getAttribute(attr);
  174. if(cur) {
  175. if(!isNaN(cur)) {
  176. element.setAttribute(attr, (cur / typeMap_[unit]) + unit);
  177. } else {
  178. // Convert existing?
  179. }
  180. }
  181. }
  182. };
  183. // Function: svgedit.units.convertToNum
  184. // Converts given values to numbers. Attributes must be supplied in
  185. // case a percentage is given
  186. //
  187. // Parameters:
  188. // attr - String with the name of the attribute associated with the value
  189. // val - String with the attribute value to convert
  190. svgedit.units.convertToNum = function(attr, val) {
  191. // Return a number if that's what it already is
  192. if(!isNaN(val)) return val-0;
  193. if(val.substr(-1) === '%') {
  194. // Deal with percentage, depends on attribute
  195. var num = val.substr(0, val.length-1)/100;
  196. var width = elementContainer_.getWidth();
  197. var height = elementContainer_.getHeight();
  198. if(w_attrs.indexOf(attr) >= 0) {
  199. return num * width;
  200. } else if(h_attrs.indexOf(attr) >= 0) {
  201. return num * height;
  202. } else {
  203. return num * Math.sqrt((width*width) + (height*height))/Math.sqrt(2);
  204. }
  205. } else {
  206. var unit = val.substr(-2);
  207. var num = val.substr(0, val.length-2);
  208. // Note that this multiplication turns the string into a number
  209. return num * typeMap_[unit];
  210. }
  211. };
  212. // Function: svgedit.units.isValidUnit
  213. // Check if an attribute's value is in a valid format
  214. //
  215. // Parameters:
  216. // attr - String with the name of the attribute associated with the value
  217. // val - String with the attribute value to check
  218. svgedit.units.isValidUnit = function(attr, val) {
  219. var valid = false;
  220. if(unit_attrs.indexOf(attr) >= 0) {
  221. // True if it's just a number
  222. if(!isNaN(val)) {
  223. valid = true;
  224. } else {
  225. // Not a number, check if it has a valid unit
  226. val = val.toLowerCase();
  227. $.each(typeMap_, function(unit) {
  228. if(valid) return;
  229. var re = new RegExp('^-?[\\d\\.]+' + unit + '$');
  230. if(re.test(val)) valid = true;
  231. });
  232. }
  233. } else if (attr == "id") {
  234. // if we're trying to change the id, make sure it's not already present in the doc
  235. // and the id value is valid.
  236. var result = false;
  237. // because getElem() can throw an exception in the case of an invalid id
  238. // (according to http://www.w3.org/TR/xml-id/ IDs must be a NCName)
  239. // we wrap it in an exception and only return true if the ID was valid and
  240. // not already present
  241. try {
  242. var elem = elementContainer_.getElement(val);
  243. result = (elem == null);
  244. } catch(e) {}
  245. return result;
  246. } else {
  247. valid = true;
  248. }
  249. return valid;
  250. };
  251. })();