jquery.svg.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. /* http://keith-wood.name/svg.html
  2. SVG for jQuery v1.4.5.
  3. Written by Keith Wood (kbwood{at}iinet.com.au) August 2007.
  4. Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and
  5. MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
  6. Please attribute the author if you use it. */
  7. (function($) { // Hide scope, no $ conflict
  8. /* SVG manager.
  9. Use the singleton instance of this class, $.svg,
  10. to interact with the SVG functionality. */
  11. function SVGManager() {
  12. this._settings = []; // Settings to be remembered per SVG object
  13. this._extensions = []; // List of SVG extensions added to SVGWrapper
  14. // for each entry [0] is extension name, [1] is extension class (function)
  15. // the function takes one parameter - the SVGWrapper instance
  16. this.regional = []; // Localisations, indexed by language, '' for default (English)
  17. this.regional[''] = {errorLoadingText: 'Error loading',
  18. notSupportedText: 'This browser does not support SVG'};
  19. this.local = this.regional['']; // Current localisation
  20. this._uuid = new Date().getTime();
  21. this._renesis = detectActiveX('RenesisX.RenesisCtrl');
  22. }
  23. /* Determine whether a given ActiveX control is available.
  24. @param classId (string) the ID for the ActiveX control
  25. @return (boolean) true if found, false if not */
  26. function detectActiveX(classId) {
  27. try {
  28. return !!(window.ActiveXObject && new ActiveXObject(classId));
  29. }
  30. catch (e) {
  31. return false;
  32. }
  33. }
  34. var PROP_NAME = 'svgwrapper';
  35. $.extend(SVGManager.prototype, {
  36. /* Class name added to elements to indicate already configured with SVG. */
  37. markerClassName: 'hasSVG',
  38. /* SVG namespace. */
  39. svgNS: 'http://www.w3.org/2000/svg',
  40. /* XLink namespace. */
  41. xlinkNS: 'http://www.w3.org/1999/xlink',
  42. /* SVG wrapper class. */
  43. _wrapperClass: SVGWrapper,
  44. /* Camel-case versions of attribute names containing dashes or are reserved words. */
  45. _attrNames: {class_: 'class', in_: 'in',
  46. alignmentBaseline: 'alignment-baseline', baselineShift: 'baseline-shift',
  47. clipPath: 'clip-path', clipRule: 'clip-rule',
  48. colorInterpolation: 'color-interpolation',
  49. colorInterpolationFilters: 'color-interpolation-filters',
  50. colorRendering: 'color-rendering', dominantBaseline: 'dominant-baseline',
  51. enableBackground: 'enable-background', fillOpacity: 'fill-opacity',
  52. fillRule: 'fill-rule', floodColor: 'flood-color',
  53. floodOpacity: 'flood-opacity', fontFamily: 'font-family',
  54. fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust',
  55. fontStretch: 'font-stretch', fontStyle: 'font-style',
  56. fontVariant: 'font-variant', fontWeight: 'font-weight',
  57. glyphOrientationHorizontal: 'glyph-orientation-horizontal',
  58. glyphOrientationVertical: 'glyph-orientation-vertical',
  59. horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x',
  60. imageRendering: 'image-rendering', letterSpacing: 'letter-spacing',
  61. lightingColor: 'lighting-color', markerEnd: 'marker-end',
  62. markerMid: 'marker-mid', markerStart: 'marker-start',
  63. stopColor: 'stop-color', stopOpacity: 'stop-opacity',
  64. strikethroughPosition: 'strikethrough-position',
  65. strikethroughThickness: 'strikethrough-thickness',
  66. strokeDashArray: 'stroke-dasharray', strokeDashOffset: 'stroke-dashoffset',
  67. strokeLineCap: 'stroke-linecap', strokeLineJoin: 'stroke-linejoin',
  68. strokeMiterLimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity',
  69. strokeWidth: 'stroke-width', textAnchor: 'text-anchor',
  70. textDecoration: 'text-decoration', textRendering: 'text-rendering',
  71. underlinePosition: 'underline-position', underlineThickness: 'underline-thickness',
  72. vertAdvY: 'vert-adv-y', vertOriginY: 'vert-origin-y',
  73. wordSpacing: 'word-spacing', writingMode: 'writing-mode'},
  74. /* Add the SVG object to its container. */
  75. _attachSVG: function(container, settings) {
  76. var svg = (container.namespaceURI == this.svgNS ? container : null);
  77. var container = (svg ? null : container);
  78. if ($(container || svg).hasClass(this.markerClassName)) {
  79. return;
  80. }
  81. if (typeof settings == 'string') {
  82. settings = {loadURL: settings};
  83. }
  84. else if (typeof settings == 'function') {
  85. settings = {onLoad: settings};
  86. }
  87. $(container || svg).addClass(this.markerClassName);
  88. try {
  89. if (!svg) {
  90. svg = document.createElementNS(this.svgNS, 'svg');
  91. svg.setAttribute('version', '1.1');
  92. if (container.clientWidth > 0) {
  93. svg.setAttribute('width', container.clientWidth);
  94. }
  95. if (container.clientHeight > 0) {
  96. svg.setAttribute('height', container.clientHeight);
  97. }
  98. container.appendChild(svg);
  99. }
  100. this._afterLoad(container, svg, settings || {});
  101. }
  102. catch (e) {
  103. if ($.browser.msie) {
  104. if (!container.id) {
  105. container.id = 'svg' + (this._uuid++);
  106. }
  107. this._settings[container.id] = settings;
  108. container.innerHTML = '<embed type="image/svg+xml" width="100%" ' +
  109. 'height="100%" src="' + (settings.initPath || '') + 'blank.svg" ' +
  110. 'pluginspage="http://www.adobe.com/svg/viewer/install/main.html"/>';
  111. }
  112. else {
  113. container.innerHTML = '<p class="svg_error">' +
  114. this.local.notSupportedText + '</p>';
  115. }
  116. }
  117. },
  118. /* SVG callback after loading - register SVG root. */
  119. _registerSVG: function() {
  120. for (var i = 0; i < document.embeds.length; i++) { // Check all
  121. var container = document.embeds[i].parentNode;
  122. if (!$(container).hasClass($.svg.markerClassName) || // Not SVG
  123. $.data(container, PROP_NAME)) { // Already done
  124. continue;
  125. }
  126. var svg = null;
  127. try {
  128. svg = document.embeds[i].getSVGDocument();
  129. }
  130. catch(e) {
  131. setTimeout($.svg._registerSVG, 250); // Renesis takes longer to load
  132. return;
  133. }
  134. svg = (svg ? svg.documentElement : null);
  135. if (svg) {
  136. $.svg._afterLoad(container, svg);
  137. }
  138. }
  139. },
  140. /* Post-processing once loaded. */
  141. _afterLoad: function(container, svg, settings) {
  142. var settings = settings || this._settings[container.id];
  143. this._settings[container ? container.id : ''] = null;
  144. var wrapper = new this._wrapperClass(svg, container);
  145. $.data(container || svg, PROP_NAME, wrapper);
  146. try {
  147. if (settings.loadURL) { // Load URL
  148. wrapper.load(settings.loadURL, settings);
  149. }
  150. if (settings.settings) { // Additional settings
  151. wrapper.configure(settings.settings);
  152. }
  153. if (settings.onLoad && !settings.loadURL) { // Onload callback
  154. settings.onLoad.apply(container || svg, [wrapper]);
  155. }
  156. }
  157. catch (e) {
  158. alert(e);
  159. }
  160. },
  161. /* Return the SVG wrapper created for a given container.
  162. @param container (string) selector for the container or
  163. (element) the container for the SVG object or
  164. jQuery collection - first entry is the container
  165. @return (SVGWrapper) the corresponding SVG wrapper element, or null if not attached */
  166. _getSVG: function(container) {
  167. container = (typeof container == 'string' ? $(container)[0] :
  168. (container.jquery ? container[0] : container));
  169. return $.data(container, PROP_NAME);
  170. },
  171. /* Remove the SVG functionality from a div.
  172. @param container (element) the container for the SVG object */
  173. _destroySVG: function(container) {
  174. var $container = $(container);
  175. if (!$container.hasClass(this.markerClassName)) {
  176. return;
  177. }
  178. $container.removeClass(this.markerClassName);
  179. if (container.namespaceURI != this.svgNS) {
  180. $container.empty();
  181. }
  182. $.removeData(container, PROP_NAME);
  183. },
  184. /* Extend the SVGWrapper object with an embedded class.
  185. The constructor function must take a single parameter that is
  186. a reference to the owning SVG root object. This allows the
  187. extension to access the basic SVG functionality.
  188. @param name (string) the name of the SVGWrapper attribute to access the new class
  189. @param extClass (function) the extension class constructor */
  190. addExtension: function(name, extClass) {
  191. this._extensions.push([name, extClass]);
  192. },
  193. /* Does this node belong to SVG?
  194. @param node (element) the node to be tested
  195. @return (boolean) true if an SVG node, false if not */
  196. isSVGElem: function(node) {
  197. return (node.nodeType == 1 && node.namespaceURI == $.svg.svgNS);
  198. }
  199. });
  200. /* The main SVG interface, which encapsulates the SVG element.
  201. Obtain a reference from $().svg('get') */
  202. function SVGWrapper(svg, container) {
  203. this._svg = svg; // The SVG root node
  204. this._container = container; // The containing div
  205. for (var i = 0; i < $.svg._extensions.length; i++) {
  206. var extension = $.svg._extensions[i];
  207. this[extension[0]] = new extension[1](this);
  208. }
  209. }
  210. $.extend(SVGWrapper.prototype, {
  211. /* Retrieve the width of the SVG object. */
  212. _width: function() {
  213. return (this._container ? this._container.clientWidth : this._svg.width);
  214. },
  215. /* Retrieve the height of the SVG object. */
  216. _height: function() {
  217. return (this._container ? this._container.clientHeight : this._svg.height);
  218. },
  219. /* Retrieve the root SVG element.
  220. @return the top-level SVG element */
  221. root: function() {
  222. return this._svg;
  223. },
  224. /* Configure a SVG node.
  225. @param node (element, optional) the node to configure
  226. @param settings (object) additional settings for the root
  227. @param clear (boolean) true to remove existing attributes first,
  228. false to add to what is already there (optional)
  229. @return (SVGWrapper) this root */
  230. configure: function(node, settings, clear) {
  231. if (!node.nodeName) {
  232. clear = settings;
  233. settings = node;
  234. node = this._svg;
  235. }
  236. if (clear) {
  237. for (var i = node.attributes.length - 1; i >= 0; i--) {
  238. var attr = node.attributes.item(i);
  239. if (!(attr.nodeName == 'onload' || attr.nodeName == 'version' ||
  240. attr.nodeName.substring(0, 5) == 'xmlns')) {
  241. node.attributes.removeNamedItem(attr.nodeName);
  242. }
  243. }
  244. }
  245. for (var attrName in settings) {
  246. node.setAttribute($.svg._attrNames[attrName] || attrName, settings[attrName]);
  247. }
  248. return this;
  249. },
  250. /* Locate a specific element in the SVG document.
  251. @param id (string) the element's identifier
  252. @return (element) the element reference, or null if not found */
  253. getElementById: function(id) {
  254. return this._svg.ownerDocument.getElementById(id);
  255. },
  256. /* Change the attributes for a SVG node.
  257. @param element (SVG element) the node to change
  258. @param settings (object) the new settings
  259. @return (SVGWrapper) this root */
  260. change: function(element, settings) {
  261. if (element) {
  262. for (var name in settings) {
  263. if (settings[name] == null) {
  264. element.removeAttribute($.svg._attrNames[name] || name);
  265. }
  266. else {
  267. element.setAttribute($.svg._attrNames[name] || name, settings[name]);
  268. }
  269. }
  270. }
  271. return this;
  272. },
  273. /* Check for parent being absent and adjust arguments accordingly. */
  274. _args: function(values, names, optSettings) {
  275. names.splice(0, 0, 'parent');
  276. names.splice(names.length, 0, 'settings');
  277. var args = {};
  278. var offset = 0;
  279. if (values[0] != null && values[0].jquery) {
  280. values[0] = values[0][0];
  281. }
  282. if (values[0] != null && !(typeof values[0] == 'object' && values[0].nodeName)) {
  283. args['parent'] = null;
  284. offset = 1;
  285. }
  286. for (var i = 0; i < values.length; i++) {
  287. args[names[i + offset]] = values[i];
  288. }
  289. if (optSettings) {
  290. $.each(optSettings, function(i, value) {
  291. if (typeof args[value] == 'object') {
  292. args.settings = args[value];
  293. args[value] = null;
  294. }
  295. });
  296. }
  297. return args;
  298. },
  299. /* Add a title.
  300. @param parent (element or jQuery) the parent node for the new title (optional)
  301. @param text (string) the text of the title
  302. @param settings (object) additional settings for the title (optional)
  303. @return (element) the new title node */
  304. title: function(parent, text, settings) {
  305. var args = this._args(arguments, ['text']);
  306. var node = this._makeNode(args.parent, 'title', args.settings || {});
  307. node.appendChild(this._svg.ownerDocument.createTextNode(args.text));
  308. return node;
  309. },
  310. /* Add a description.
  311. @param parent (element or jQuery) the parent node for the new description (optional)
  312. @param text (string) the text of the description
  313. @param settings (object) additional settings for the description (optional)
  314. @return (element) the new description node */
  315. describe: function(parent, text, settings) {
  316. var args = this._args(arguments, ['text']);
  317. var node = this._makeNode(args.parent, 'desc', args.settings || {});
  318. node.appendChild(this._svg.ownerDocument.createTextNode(args.text));
  319. return node;
  320. },
  321. /* Add a definitions node.
  322. @param parent (element or jQuery) the parent node for the new definitions (optional)
  323. @param id (string) the ID of this definitions (optional)
  324. @param settings (object) additional settings for the definitions (optional)
  325. @return (element) the new definitions node */
  326. defs: function(parent, id, settings) {
  327. var args = this._args(arguments, ['id'], ['id']);
  328. return this._makeNode(args.parent, 'defs', $.extend(
  329. (args.id ? {id: args.id} : {}), args.settings || {}));
  330. },
  331. /* Add a symbol definition.
  332. @param parent (element or jQuery) the parent node for the new symbol (optional)
  333. @param id (string) the ID of this symbol
  334. @param x1 (number) the left coordinate for this symbol
  335. @param y1 (number) the top coordinate for this symbol
  336. @param width (number) the width of this symbol
  337. @param height (number) the height of this symbol
  338. @param settings (object) additional settings for the symbol (optional)
  339. @return (element) the new symbol node */
  340. symbol: function(parent, id, x1, y1, width, height, settings) {
  341. var args = this._args(arguments, ['id', 'x1', 'y1', 'width', 'height']);
  342. return this._makeNode(args.parent, 'symbol', $.extend({id: args.id,
  343. viewBox: args.x1 + ' ' + args.y1 + ' ' + args.width + ' ' + args.height},
  344. args.settings || {}));
  345. },
  346. /* Add a marker definition.
  347. @param parent (element or jQuery) the parent node for the new marker (optional)
  348. @param id (string) the ID of this marker
  349. @param refX (number) the x-coordinate for the reference point
  350. @param refY (number) the y-coordinate for the reference point
  351. @param mWidth (number) the marker viewport width
  352. @param mHeight (number) the marker viewport height
  353. @param orient (string or int) 'auto' or angle (degrees) (optional)
  354. @param settings (object) additional settings for the marker (optional)
  355. @return (element) the new marker node */
  356. marker: function(parent, id, refX, refY, mWidth, mHeight, orient, settings) {
  357. var args = this._args(arguments, ['id', 'refX', 'refY',
  358. 'mWidth', 'mHeight', 'orient'], ['orient']);
  359. return this._makeNode(args.parent, 'marker', $.extend(
  360. {id: args.id, refX: args.refX, refY: args.refY, markerWidth: args.mWidth,
  361. markerHeight: args.mHeight, orient: args.orient || 'auto'}, args.settings || {}));
  362. },
  363. /* Add a style node.
  364. @param parent (element or jQuery) the parent node for the new node (optional)
  365. @param styles (string) the CSS styles
  366. @param settings (object) additional settings for the node (optional)
  367. @return (element) the new style node */
  368. style: function(parent, styles, settings) {
  369. var args = this._args(arguments, ['styles']);
  370. var node = this._makeNode(args.parent, 'style', $.extend(
  371. {type: 'text/css'}, args.settings || {}));
  372. node.appendChild(this._svg.ownerDocument.createTextNode(args.styles));
  373. if ($.browser.opera) {
  374. $('head').append('<style type="text/css">' + args.styles + '</style>');
  375. }
  376. return node;
  377. },
  378. /* Add a script node.
  379. @param parent (element or jQuery) the parent node for the new node (optional)
  380. @param script (string) the JavaScript code
  381. @param type (string) the MIME type for the code (optional, default 'text/javascript')
  382. @param settings (object) additional settings for the node (optional)
  383. @return (element) the new script node */
  384. script: function(parent, script, type, settings) {
  385. var args = this._args(arguments, ['script', 'type'], ['type']);
  386. var node = this._makeNode(args.parent, 'script', $.extend(
  387. {type: args.type || 'text/javascript'}, args.settings || {}));
  388. node.appendChild(this._svg.ownerDocument.createTextNode(args.script));
  389. if (!$.browser.mozilla) {
  390. $.globalEval(args.script);
  391. }
  392. return node;
  393. },
  394. /* Add a linear gradient definition.
  395. Specify all of x1, y1, x2, y2 or none of them.
  396. @param parent (element or jQuery) the parent node for the new gradient (optional)
  397. @param id (string) the ID for this gradient
  398. @param stops (string[][]) the gradient stops, each entry is
  399. [0] is offset (0.0-1.0 or 0%-100%), [1] is colour,
  400. [2] is opacity (optional)
  401. @param x1 (number) the x-coordinate of the gradient start (optional)
  402. @param y1 (number) the y-coordinate of the gradient start (optional)
  403. @param x2 (number) the x-coordinate of the gradient end (optional)
  404. @param y2 (number) the y-coordinate of the gradient end (optional)
  405. @param settings (object) additional settings for the gradient (optional)
  406. @return (element) the new gradient node */
  407. linearGradient: function(parent, id, stops, x1, y1, x2, y2, settings) {
  408. var args = this._args(arguments,
  409. ['id', 'stops', 'x1', 'y1', 'x2', 'y2'], ['x1']);
  410. var sets = $.extend({id: args.id},
  411. (args.x1 != null ? {x1: args.x1, y1: args.y1, x2: args.x2, y2: args.y2} : {}));
  412. return this._gradient(args.parent, 'linearGradient',
  413. $.extend(sets, args.settings || {}), args.stops);
  414. },
  415. /* Add a radial gradient definition.
  416. Specify all of cx, cy, r, fx, fy or none of them.
  417. @param parent (element or jQuery) the parent node for the new gradient (optional)
  418. @param id (string) the ID for this gradient
  419. @param stops (string[][]) the gradient stops, each entry
  420. [0] is offset, [1] is colour, [2] is opacity (optional)
  421. @param cx (number) the x-coordinate of the largest circle centre (optional)
  422. @param cy (number) the y-coordinate of the largest circle centre (optional)
  423. @param r (number) the radius of the largest circle (optional)
  424. @param fx (number) the x-coordinate of the gradient focus (optional)
  425. @param fy (number) the y-coordinate of the gradient focus (optional)
  426. @param settings (object) additional settings for the gradient (optional)
  427. @return (element) the new gradient node */
  428. radialGradient: function(parent, id, stops, cx, cy, r, fx, fy, settings) {
  429. var args = this._args(arguments,
  430. ['id', 'stops', 'cx', 'cy', 'r', 'fx', 'fy'], ['cx']);
  431. var sets = $.extend({id: args.id}, (args.cx != null ?
  432. {cx: args.cx, cy: args.cy, r: args.r, fx: args.fx, fy: args.fy} : {}));
  433. return this._gradient(args.parent, 'radialGradient',
  434. $.extend(sets, args.settings || {}), args.stops);
  435. },
  436. /* Add a gradient node. */
  437. _gradient: function(parent, name, settings, stops) {
  438. var node = this._makeNode(parent, name, settings);
  439. for (var i = 0; i < stops.length; i++) {
  440. var stop = stops[i];
  441. this._makeNode(node, 'stop', $.extend(
  442. {offset: stop[0], stopColor: stop[1]},
  443. (stop[2] != null ? {stopOpacity: stop[2]} : {})));
  444. }
  445. return node;
  446. },
  447. /* Add a pattern definition.
  448. Specify all of vx, vy, xwidth, vheight or none of them.
  449. @param parent (element or jQuery) the parent node for the new pattern (optional)
  450. @param id (string) the ID for this pattern
  451. @param x (number) the x-coordinate for the left edge of the pattern
  452. @param y (number) the y-coordinate for the top edge of the pattern
  453. @param width (number) the width of the pattern
  454. @param height (number) the height of the pattern
  455. @param vx (number) the minimum x-coordinate for view box (optional)
  456. @param vy (number) the minimum y-coordinate for the view box (optional)
  457. @param vwidth (number) the width of the view box (optional)
  458. @param vheight (number) the height of the view box (optional)
  459. @param settings (object) additional settings for the pattern (optional)
  460. @return (element) the new pattern node */
  461. pattern: function(parent, id, x, y, width, height, vx, vy, vwidth, vheight, settings) {
  462. var args = this._args(arguments, ['id', 'x', 'y', 'width', 'height',
  463. 'vx', 'vy', 'vwidth', 'vheight'], ['vx']);
  464. var sets = $.extend({id: args.id, x: args.x, y: args.y,
  465. width: args.width, height: args.height}, (args.vx != null ?
  466. {viewBox: args.vx + ' ' + args.vy + ' ' + args.vwidth + ' ' + args.vheight} : {}));
  467. return this._makeNode(args.parent, 'pattern', $.extend(sets, args.settings || {}));
  468. },
  469. /* Add a clip path definition.
  470. @param parent (element) the parent node for the new element (optional)
  471. @param id (string) the ID for this path
  472. @param units (string) either 'userSpaceOnUse' (default) or 'objectBoundingBox' (optional)
  473. @return (element) the new clipPath node */
  474. clipPath: function(parent, id, units, settings) {
  475. var args = this._args(arguments, ['id', 'units']);
  476. args.units = args.units || 'userSpaceOnUse';
  477. return this._makeNode(args.parent, 'clipPath', $.extend(
  478. {id: args.id, clipPathUnits: args.units}, args.settings || {}));
  479. },
  480. /* Add a mask definition.
  481. @param parent (element or jQuery) the parent node for the new mask (optional)
  482. @param id (string) the ID for this mask
  483. @param x (number) the x-coordinate for the left edge of the mask
  484. @param y (number) the y-coordinate for the top edge of the mask
  485. @param width (number) the width of the mask
  486. @param height (number) the height of the mask
  487. @param settings (object) additional settings for the mask (optional)
  488. @return (element) the new mask node */
  489. mask: function(parent, id, x, y, width, height, settings) {
  490. var args = this._args(arguments, ['id', 'x', 'y', 'width', 'height']);
  491. return this._makeNode(args.parent, 'mask', $.extend(
  492. {id: args.id, x: args.x, y: args.y, width: args.width, height: args.height},
  493. args.settings || {}));
  494. },
  495. /* Create a new path object.
  496. @return (SVGPath) a new path object */
  497. createPath: function() {
  498. return new SVGPath();
  499. },
  500. /* Create a new text object.
  501. @return (SVGText) a new text object */
  502. createText: function() {
  503. return new SVGText();
  504. },
  505. /* Add an embedded SVG element.
  506. Specify all of vx, vy, vwidth, vheight or none of them.
  507. @param parent (element or jQuery) the parent node for the new node (optional)
  508. @param x (number) the x-coordinate for the left edge of the node
  509. @param y (number) the y-coordinate for the top edge of the node
  510. @param width (number) the width of the node
  511. @param height (number) the height of the node
  512. @param vx (number) the minimum x-coordinate for view box (optional)
  513. @param vy (number) the minimum y-coordinate for the view box (optional)
  514. @param vwidth (number) the width of the view box (optional)
  515. @param vheight (number) the height of the view box (optional)
  516. @param settings (object) additional settings for the node (optional)
  517. @return (element) the new node */
  518. svg: function(parent, x, y, width, height, vx, vy, vwidth, vheight, settings) {
  519. var args = this._args(arguments, ['x', 'y', 'width', 'height',
  520. 'vx', 'vy', 'vwidth', 'vheight'], ['vx']);
  521. var sets = $.extend({x: args.x, y: args.y, width: args.width, height: args.height},
  522. (args.vx != null ? {viewBox: args.vx + ' ' + args.vy + ' ' +
  523. args.vwidth + ' ' + args.vheight} : {}));
  524. return this._makeNode(args.parent, 'svg', $.extend(sets, args.settings || {}));
  525. },
  526. /* Create a group.
  527. @param parent (element or jQuery) the parent node for the new group (optional)
  528. @param id (string) the ID of this group (optional)
  529. @param settings (object) additional settings for the group (optional)
  530. @return (element) the new group node */
  531. group: function(parent, id, settings) {
  532. var args = this._args(arguments, ['id'], ['id']);
  533. return this._makeNode(args.parent, 'g', $.extend({id: args.id}, args.settings || {}));
  534. },
  535. /* Add a usage reference.
  536. Specify all of x, y, width, height or none of them.
  537. @param parent (element or jQuery) the parent node for the new node (optional)
  538. @param x (number) the x-coordinate for the left edge of the node (optional)
  539. @param y (number) the y-coordinate for the top edge of the node (optional)
  540. @param width (number) the width of the node (optional)
  541. @param height (number) the height of the node (optional)
  542. @param ref (string) the ID of the definition node
  543. @param settings (object) additional settings for the node (optional)
  544. @return (element) the new node */
  545. use: function(parent, x, y, width, height, ref, settings) {
  546. var args = this._args(arguments, ['x', 'y', 'width', 'height', 'ref']);
  547. if (typeof args.x == 'string') {
  548. args.ref = args.x;
  549. args.settings = args.y;
  550. args.x = args.y = args.width = args.height = null;
  551. }
  552. var node = this._makeNode(args.parent, 'use', $.extend(
  553. {x: args.x, y: args.y, width: args.width, height: args.height},
  554. args.settings || {}));
  555. node.setAttributeNS($.svg.xlinkNS, 'href', args.ref);
  556. return node;
  557. },
  558. /* Add a link, which applies to all child elements.
  559. @param parent (element or jQuery) the parent node for the new link (optional)
  560. @param ref (string) the target URL
  561. @param settings (object) additional settings for the link (optional)
  562. @return (element) the new link node */
  563. link: function(parent, ref, settings) {
  564. var args = this._args(arguments, ['ref']);
  565. var node = this._makeNode(args.parent, 'a', args.settings);
  566. node.setAttributeNS($.svg.xlinkNS, 'href', args.ref);
  567. return node;
  568. },
  569. /* Add an image.
  570. @param parent (element or jQuery) the parent node for the new image (optional)
  571. @param x (number) the x-coordinate for the left edge of the image
  572. @param y (number) the y-coordinate for the top edge of the image
  573. @param width (number) the width of the image
  574. @param height (number) the height of the image
  575. @param ref (string) the path to the image
  576. @param settings (object) additional settings for the image (optional)
  577. @return (element) the new image node */
  578. image: function(parent, x, y, width, height, ref, settings) {
  579. var args = this._args(arguments, ['x', 'y', 'width', 'height', 'ref']);
  580. var node = this._makeNode(args.parent, 'image', $.extend(
  581. {x: args.x, y: args.y, width: args.width, height: args.height},
  582. args.settings || {}));
  583. node.setAttributeNS($.svg.xlinkNS, 'href', args.ref);
  584. return node;
  585. },
  586. /* Draw a path.
  587. @param parent (element or jQuery) the parent node for the new shape (optional)
  588. @param path (string or SVGPath) the path to draw
  589. @param settings (object) additional settings for the shape (optional)
  590. @return (element) the new shape node */
  591. path: function(parent, path, settings) {
  592. var args = this._args(arguments, ['path']);
  593. return this._makeNode(args.parent, 'path', $.extend(
  594. {d: (args.path.path ? args.path.path() : args.path)}, args.settings || {}));
  595. },
  596. /* Draw a rectangle.
  597. Specify both of rx and ry or neither.
  598. @param parent (element or jQuery) the parent node for the new shape (optional)
  599. @param x (number) the x-coordinate for the left edge of the rectangle
  600. @param y (number) the y-coordinate for the top edge of the rectangle
  601. @param width (number) the width of the rectangle
  602. @param height (number) the height of the rectangle
  603. @param rx (number) the x-radius of the ellipse for the rounded corners (optional)
  604. @param ry (number) the y-radius of the ellipse for the rounded corners (optional)
  605. @param settings (object) additional settings for the shape (optional)
  606. @return (element) the new shape node */
  607. rect: function(parent, x, y, width, height, rx, ry, settings) {
  608. var args = this._args(arguments, ['x', 'y', 'width', 'height', 'rx', 'ry'], ['rx']);
  609. return this._makeNode(args.parent, 'rect', $.extend(
  610. {x: args.x, y: args.y, width: args.width, height: args.height},
  611. (args.rx ? {rx: args.rx, ry: args.ry} : {}), args.settings || {}));
  612. },
  613. /* Draw a circle.
  614. @param parent (element or jQuery) the parent node for the new shape (optional)
  615. @param cx (number) the x-coordinate for the centre of the circle
  616. @param cy (number) the y-coordinate for the centre of the circle
  617. @param r (number) the radius of the circle
  618. @param settings (object) additional settings for the shape (optional)
  619. @return (element) the new shape node */
  620. circle: function(parent, cx, cy, r, settings) {
  621. var args = this._args(arguments, ['cx', 'cy', 'r']);
  622. return this._makeNode(args.parent, 'circle', $.extend(
  623. {cx: args.cx, cy: args.cy, r: args.r}, args.settings || {}));
  624. },
  625. /* Draw an ellipse.
  626. @param parent (element or jQuery) the parent node for the new shape (optional)
  627. @param cx (number) the x-coordinate for the centre of the ellipse
  628. @param cy (number) the y-coordinate for the centre of the ellipse
  629. @param rx (number) the x-radius of the ellipse
  630. @param ry (number) the y-radius of the ellipse
  631. @param settings (object) additional settings for the shape (optional)
  632. @return (element) the new shape node */
  633. ellipse: function(parent, cx, cy, rx, ry, settings) {
  634. var args = this._args(arguments, ['cx', 'cy', 'rx', 'ry']);
  635. return this._makeNode(args.parent, 'ellipse', $.extend(
  636. {cx: args.cx, cy: args.cy, rx: args.rx, ry: args.ry}, args.settings || {}));
  637. },
  638. /* Draw a line.
  639. @param parent (element or jQuery) the parent node for the new shape (optional)
  640. @param x1 (number) the x-coordinate for the start of the line
  641. @param y1 (number) the y-coordinate for the start of the line
  642. @param x2 (number) the x-coordinate for the end of the line
  643. @param y2 (number) the y-coordinate for the end of the line
  644. @param settings (object) additional settings for the shape (optional)
  645. @return (element) the new shape node */
  646. line: function(parent, x1, y1, x2, y2, settings) {
  647. var args = this._args(arguments, ['x1', 'y1', 'x2', 'y2']);
  648. return this._makeNode(args.parent, 'line', $.extend(
  649. {x1: args.x1, y1: args.y1, x2: args.x2, y2: args.y2}, args.settings || {}));
  650. },
  651. /* Draw a polygonal line.
  652. @param parent (element or jQuery) the parent node for the new shape (optional)
  653. @param points (number[][]) the x-/y-coordinates for the points on the line
  654. @param settings (object) additional settings for the shape (optional)
  655. @return (element) the new shape node */
  656. polyline: function(parent, points, settings) {
  657. var args = this._args(arguments, ['points']);
  658. return this._poly(args.parent, 'polyline', args.points, args.settings);
  659. },
  660. /* Draw a polygonal shape.
  661. @param parent (element or jQuery) the parent node for the new shape (optional)
  662. @param points (number[][]) the x-/y-coordinates for the points on the shape
  663. @param settings (object) additional settings for the shape (optional)
  664. @return (element) the new shape node */
  665. polygon: function(parent, points, settings) {
  666. var args = this._args(arguments, ['points']);
  667. return this._poly(args.parent, 'polygon', args.points, args.settings);
  668. },
  669. /* Draw a polygonal line or shape. */
  670. _poly: function(parent, name, points, settings) {
  671. var ps = '';
  672. for (var i = 0; i < points.length; i++) {
  673. ps += points[i].join() + ' ';
  674. }
  675. return this._makeNode(parent, name, $.extend(
  676. {points: $.trim(ps)}, settings || {}));
  677. },
  678. /* Draw text.
  679. Specify both of x and y or neither of them.
  680. @param parent (element or jQuery) the parent node for the text (optional)
  681. @param x (number or number[]) the x-coordinate(s) for the text (optional)
  682. @param y (number or number[]) the y-coordinate(s) for the text (optional)
  683. @param value (string) the text content or
  684. (SVGText) text with spans and references
  685. @param settings (object) additional settings for the text (optional)
  686. @return (element) the new text node */
  687. text: function(parent, x, y, value, settings) {
  688. var args = this._args(arguments, ['x', 'y', 'value']);
  689. if (typeof args.x == 'string' && arguments.length < 4) {
  690. args.value = args.x;
  691. args.settings = args.y;
  692. args.x = args.y = null;
  693. }
  694. return this._text(args.parent, 'text', args.value, $.extend(
  695. {x: (args.x && isArray(args.x) ? args.x.join(' ') : args.x),
  696. y: (args.y && isArray(args.y) ? args.y.join(' ') : args.y)},
  697. args.settings || {}));
  698. },
  699. /* Draw text along a path.
  700. @param parent (element or jQuery) the parent node for the text (optional)
  701. @param path (string) the ID of the path
  702. @param value (string) the text content or
  703. (SVGText) text with spans and references
  704. @param settings (object) additional settings for the text (optional)
  705. @return (element) the new text node */
  706. textpath: function(parent, path, value, settings) {
  707. var args = this._args(arguments, ['path', 'value']);
  708. var node = this._text(args.parent, 'textPath', args.value, args.settings || {});
  709. node.setAttributeNS($.svg.xlinkNS, 'href', args.path);
  710. return node;
  711. },
  712. /* Draw text. */
  713. _text: function(parent, name, value, settings) {
  714. var node = this._makeNode(parent, name, settings);
  715. if (typeof value == 'string') {
  716. node.appendChild(node.ownerDocument.createTextNode(value));
  717. }
  718. else {
  719. for (var i = 0; i < value._parts.length; i++) {
  720. var part = value._parts[i];
  721. if (part[0] == 'tspan') {
  722. var child = this._makeNode(node, part[0], part[2]);
  723. child.appendChild(node.ownerDocument.createTextNode(part[1]));
  724. node.appendChild(child);
  725. }
  726. else if (part[0] == 'tref') {
  727. var child = this._makeNode(node, part[0], part[2]);
  728. child.setAttributeNS($.svg.xlinkNS, 'href', part[1]);
  729. node.appendChild(child);
  730. }
  731. else if (part[0] == 'textpath') {
  732. var set = $.extend({}, part[2]);
  733. set.href = null;
  734. var child = this._makeNode(node, part[0], set);
  735. child.setAttributeNS($.svg.xlinkNS, 'href', part[2].href);
  736. child.appendChild(node.ownerDocument.createTextNode(part[1]));
  737. node.appendChild(child);
  738. }
  739. else { // straight text
  740. node.appendChild(node.ownerDocument.createTextNode(part[1]));
  741. }
  742. }
  743. }
  744. return node;
  745. },
  746. /* Add a custom SVG element.
  747. @param parent (element or jQuery) the parent node for the new element (optional)
  748. @param name (string) the name of the element
  749. @param settings (object) additional settings for the element (optional)
  750. @return (element) the new custom node */
  751. other: function(parent, name, settings) {
  752. var args = this._args(arguments, ['name']);
  753. return this._makeNode(args.parent, args.name, args.settings || {});
  754. },
  755. /* Create a shape node with the given settings. */
  756. _makeNode: function(parent, name, settings) {
  757. parent = parent || this._svg;
  758. var node = this._svg.ownerDocument.createElementNS($.svg.svgNS, name);
  759. for (var name in settings) {
  760. var value = settings[name];
  761. if (value != null && value != null &&
  762. (typeof value != 'string' || value != '')) {
  763. node.setAttribute($.svg._attrNames[name] || name, value);
  764. }
  765. }
  766. parent.appendChild(node);
  767. return node;
  768. },
  769. /* Add an existing SVG node to the diagram.
  770. @param parent (element or jQuery) the parent node for the new node (optional)
  771. @param node (element) the new node to add or
  772. (string) the jQuery selector for the node or
  773. (jQuery collection) set of nodes to add
  774. @return (SVGWrapper) this wrapper */
  775. add: function(parent, node) {
  776. var args = this._args((arguments.length == 1 ? [null, parent] : arguments), ['node']);
  777. var svg = this;
  778. args.parent = args.parent || this._svg;
  779. args.node = (args.node.jquery ? args.node : $(args.node));
  780. try {
  781. if ($.svg._renesis) {
  782. throw 'Force traversal';
  783. }
  784. args.parent.appendChild(args.node.cloneNode(true));
  785. }
  786. catch (e) {
  787. args.node.each(function() {
  788. var child = svg._cloneAsSVG(this);
  789. if (child) {
  790. args.parent.appendChild(child);
  791. }
  792. });
  793. }
  794. return this;
  795. },
  796. /* Clone an existing SVG node and add it to the diagram.
  797. @param parent (element or jQuery) the parent node for the new node (optional)
  798. @param node (element) the new node to add or
  799. (string) the jQuery selector for the node or
  800. (jQuery collection) set of nodes to add
  801. @return (element[]) collection of new nodes */
  802. clone: function(parent, node) {
  803. var svg = this;
  804. var args = this._args((arguments.length == 1 ? [null, parent] : arguments), ['node']);
  805. args.parent = args.parent || this._svg;
  806. args.node = (args.node.jquery ? args.node : $(args.node));
  807. var newNodes = [];
  808. args.node.each(function() {
  809. var child = svg._cloneAsSVG(this);
  810. if (child) {
  811. child.id = '';
  812. args.parent.appendChild(child);
  813. newNodes.push(child);
  814. }
  815. });
  816. return newNodes;
  817. },
  818. /* SVG nodes must belong to the SVG namespace, so clone and ensure this is so.
  819. @param node (element) the SVG node to clone
  820. @return (element) the cloned node */
  821. _cloneAsSVG: function(node) {
  822. var newNode = null;
  823. if (node.nodeType == 1) { // element
  824. newNode = this._svg.ownerDocument.createElementNS(
  825. $.svg.svgNS, this._checkName(node.nodeName));
  826. for (var i = 0; i < node.attributes.length; i++) {
  827. var attr = node.attributes.item(i);
  828. if (attr.nodeName != 'xmlns' && attr.nodeValue) {
  829. if (attr.prefix == 'xlink') {
  830. newNode.setAttributeNS($.svg.xlinkNS,
  831. attr.localName || attr.baseName, attr.nodeValue);
  832. }
  833. else {
  834. newNode.setAttribute(this._checkName(attr.nodeName), attr.nodeValue);
  835. }
  836. }
  837. }
  838. for (var i = 0; i < node.childNodes.length; i++) {
  839. var child = this._cloneAsSVG(node.childNodes[i]);
  840. if (child) {
  841. newNode.appendChild(child);
  842. }
  843. }
  844. }
  845. else if (node.nodeType == 3) { // text
  846. if ($.trim(node.nodeValue)) {
  847. newNode = this._svg.ownerDocument.createTextNode(node.nodeValue);
  848. }
  849. }
  850. else if (node.nodeType == 4) { // CDATA
  851. if ($.trim(node.nodeValue)) {
  852. try {
  853. newNode = this._svg.ownerDocument.createCDATASection(node.nodeValue);
  854. }
  855. catch (e) {
  856. newNode = this._svg.ownerDocument.createTextNode(
  857. node.nodeValue.replace(/&/g, '&amp;').
  858. replace(/</g, '&lt;').replace(/>/g, '&gt;'));
  859. }
  860. }
  861. }
  862. return newNode;
  863. },
  864. /* Node names must be lower case and without SVG namespace prefix. */
  865. _checkName: function(name) {
  866. name = (name.substring(0, 1) >= 'A' && name.substring(0, 1) <= 'Z' ?
  867. name.toLowerCase() : name);
  868. return (name.substring(0, 4) == 'svg:' ? name.substring(4) : name);
  869. },
  870. /* Load an external SVG document.
  871. @param url (string) the location of the SVG document or
  872. the actual SVG content
  873. @param settings (boolean) see addTo below or
  874. (function) see onLoad below or
  875. (object) additional settings for the load with attributes below:
  876. addTo (boolean) true to add to what's already there,
  877. or false to clear the canvas first
  878. changeSize (boolean) true to allow the canvas size to change,
  879. or false to retain the original
  880. onLoad (function) callback after the document has loaded,
  881. 'this' is the container, receives SVG object and
  882. optional error message as a parameter
  883. parent (string or element or jQuery) the parent to load
  884. into, defaults to top-level svg element
  885. @return (SVGWrapper) this root */
  886. load: function(url, settings) {
  887. settings = (typeof settings == 'boolean' ? {addTo: settings} :
  888. (typeof settings == 'function' ? {onLoad: settings} :
  889. (typeof settings == 'string' ? {parent: settings} :
  890. (typeof settings == 'object' && settings.nodeName ? {parent: settings} :
  891. (typeof settings == 'object' && settings.jquery ? {parent: settings} :
  892. settings || {})))));
  893. if (!settings.parent && !settings.addTo) {
  894. this.clear(false);
  895. }
  896. var size = [this._svg.getAttribute('width'), this._svg.getAttribute('height')];
  897. var wrapper = this;
  898. // Report a problem with the load
  899. var reportError = function(message) {
  900. message = $.svg.local.errorLoadingText + ': ' + message;
  901. if (settings.onLoad) {
  902. settings.onLoad.apply(wrapper._container || wrapper._svg, [wrapper, message]);
  903. }
  904. else {
  905. wrapper.text(null, 10, 20, message);
  906. }
  907. };
  908. // Create a DOM from SVG content
  909. var loadXML4IE = function(data) {
  910. var xml = new ActiveXObject('Microsoft.XMLDOM');
  911. xml.validateOnParse = false;
  912. xml.resolveExternals = false;
  913. xml.async = false;
  914. xml.loadXML(data);
  915. if (xml.parseError.errorCode != 0) {
  916. reportError(xml.parseError.reason);
  917. return null;
  918. }
  919. return xml;
  920. };
  921. // Load the SVG DOM
  922. var loadSVG = function(data) {
  923. if (!data) {
  924. return;
  925. }
  926. if (data.documentElement.nodeName != 'svg') {
  927. var errors = data.getElementsByTagName('parsererror');
  928. var messages = (errors.length ? errors[0].getElementsByTagName('div') : []); // Safari
  929. reportError(!errors.length ? '???' :
  930. (messages.length ? messages[0] : errors[0]).firstChild.nodeValue);
  931. return;
  932. }
  933. var parent = (settings.parent ? $(settings.parent)[0] : wrapper._svg);
  934. var attrs = {};
  935. for (var i = 0; i < data.documentElement.attributes.length; i++) {
  936. var attr = data.documentElement.attributes.item(i);
  937. if (!(attr.nodeName == 'version' || attr.nodeName.substring(0, 5) == 'xmlns')) {
  938. attrs[attr.nodeName] = attr.nodeValue;
  939. }
  940. }
  941. wrapper.configure(parent, attrs, !settings.parent);
  942. var nodes = data.documentElement.childNodes;
  943. for (var i = 0; i < nodes.length; i++) {
  944. try {
  945. if ($.svg._renesis) {
  946. throw 'Force traversal';
  947. }
  948. parent.appendChild(wrapper._svg.ownerDocument.importNode(nodes[i], true));
  949. if (nodes[i].nodeName == 'script') {
  950. $.globalEval(nodes[i].textContent);
  951. }
  952. }
  953. catch (e) {
  954. wrapper.add(parent, nodes[i]);
  955. }
  956. }
  957. if (!settings.changeSize) {
  958. wrapper.configure(parent, {width: size[0], height: size[1]});
  959. }
  960. if (settings.onLoad) {
  961. settings.onLoad.apply(wrapper._container || wrapper._svg, [wrapper]);
  962. }
  963. };
  964. if (url.match('<svg')) { // Inline SVG
  965. loadSVG($.browser.msie ? loadXML4IE(url) :
  966. new DOMParser().parseFromString(url, 'text/xml'));
  967. }
  968. else { // Remote SVG
  969. $.ajax({url: url, dataType: ($.browser.msie ? 'text' : 'xml'),
  970. success: function(xml) {
  971. loadSVG($.browser.msie ? loadXML4IE(xml) : xml);
  972. }, error: function(http, message, exc) {
  973. reportError(message + (exc ? ' ' + exc.message : ''));
  974. }});
  975. }
  976. return this;
  977. },
  978. /* Delete a specified node.
  979. @param node (element or jQuery) the drawing node to remove
  980. @return (SVGWrapper) this root */
  981. remove: function(node) {
  982. node = (node.jquery ? node[0] : node);
  983. node.parentNode.removeChild(node);
  984. return this;
  985. },
  986. /* Delete everything in the current document.
  987. @param attrsToo (boolean) true to clear any root attributes as well,
  988. false to leave them (optional)
  989. @return (SVGWrapper) this root */
  990. clear: function(attrsToo) {
  991. if (attrsToo) {
  992. this.configure({}, true);
  993. }
  994. while (this._svg.firstChild) {
  995. this._svg.removeChild(this._svg.firstChild);
  996. }
  997. return this;
  998. },
  999. /* Serialise the current diagram into an SVG text document.
  1000. @param node (SVG element) the starting node (optional)
  1001. @return (string) the SVG as text */
  1002. toSVG: function(node) {
  1003. node = node || this._svg;
  1004. return (typeof XMLSerializer == 'undefined' ? this._toSVG(node) :
  1005. new XMLSerializer().serializeToString(node));
  1006. },
  1007. /* Serialise one node in the SVG hierarchy. */
  1008. _toSVG: function(node) {
  1009. var svgDoc = '';
  1010. if (!node) {
  1011. return svgDoc;
  1012. }
  1013. if (node.nodeType == 3) { // Text
  1014. svgDoc = node.nodeValue;
  1015. }
  1016. else if (node.nodeType == 4) { // CDATA
  1017. svgDoc = '<![CDATA[' + node.nodeValue + ']]>';
  1018. }
  1019. else { // Element
  1020. svgDoc = '<' + node.nodeName;
  1021. if (node.attributes) {
  1022. for (var i = 0; i < node.attributes.length; i++) {
  1023. var attr = node.attributes.item(i);
  1024. if (!($.trim(attr.nodeValue) == '' || attr.nodeValue.match(/^\[object/) ||
  1025. attr.nodeValue.match(/^function/))) {
  1026. svgDoc += ' ' + (attr.namespaceURI == $.svg.xlinkNS ? 'xlink:' : '') +
  1027. attr.nodeName + '="' + attr.nodeValue + '"';
  1028. }
  1029. }
  1030. }
  1031. if (node.firstChild) {
  1032. svgDoc += '>';
  1033. var child = node.firstChild;
  1034. while (child) {
  1035. svgDoc += this._toSVG(child);
  1036. child = child.nextSibling;
  1037. }
  1038. svgDoc += '</' + node.nodeName + '>';
  1039. }
  1040. else {
  1041. svgDoc += '/>';
  1042. }
  1043. }
  1044. return svgDoc;
  1045. }
  1046. });
  1047. /* Helper to generate an SVG path.
  1048. Obtain an instance from the SVGWrapper object.
  1049. String calls together to generate the path and use its value:
  1050. var path = root.createPath();
  1051. root.path(null, path.move(100, 100).line(300, 100).line(200, 300).close(), {fill: 'red'});
  1052. or
  1053. root.path(null, path.move(100, 100).line([[300, 100], [200, 300]]).close(), {fill: 'red'}); */
  1054. function SVGPath() {
  1055. this._path = '';
  1056. }
  1057. $.extend(SVGPath.prototype, {
  1058. /* Prepare to create a new path.
  1059. @return (SVGPath) this path */
  1060. reset: function() {
  1061. this._path = '';
  1062. return this;
  1063. },
  1064. /* Move the pointer to a position.
  1065. @param x (number) x-coordinate to move to or
  1066. (number[][]) x-/y-coordinates to move to
  1067. @param y (number) y-coordinate to move to (omitted if x is array)
  1068. @param relative (boolean) true for coordinates relative to the current point,
  1069. false for coordinates being absolute
  1070. @return (SVGPath) this path */
  1071. move: function(x, y, relative) {
  1072. relative = (isArray(x) ? y : relative);
  1073. return this._coords((relative ? 'm' : 'M'), x, y);
  1074. },
  1075. /* Draw a line to a position.
  1076. @param x (number) x-coordinate to move to or
  1077. (number[][]) x-/y-coordinates to move to
  1078. @param y (number) y-coordinate to move to (omitted if x is array)
  1079. @param relative (boolean) true for coordinates relative to the current point,
  1080. false for coordinates being absolute
  1081. @return (SVGPath) this path */
  1082. line: function(x, y, relative) {
  1083. relative = (isArray(x) ? y : relative);
  1084. return this._coords((relative ? 'l' : 'L'), x, y);
  1085. },
  1086. /* Draw a horizontal line to a position.
  1087. @param x (number) x-coordinate to draw to or
  1088. (number[]) x-coordinates to draw to
  1089. @param relative (boolean) true for coordinates relative to the current point,
  1090. false for coordinates being absolute
  1091. @return (SVGPath) this path */
  1092. horiz: function(x, relative) {
  1093. this._path += (relative ? 'h' : 'H') + (isArray(x) ? x.join(' ') : x);
  1094. return this;
  1095. },
  1096. /* Draw a vertical line to a position.
  1097. @param y (number) y-coordinate to draw to or
  1098. (number[]) y-coordinates to draw to
  1099. @param relative (boolean) true for coordinates relative to the current point,
  1100. false for coordinates being absolute
  1101. @return (SVGPath) this path */
  1102. vert: function(y, relative) {
  1103. this._path += (relative ? 'v' : 'V') + (isArray(y) ? y.join(' ') : y);
  1104. return this;
  1105. },
  1106. /* Draw a cubic Bézier curve.
  1107. @param x1 (number) x-coordinate of beginning control point or
  1108. (number[][]) x-/y-coordinates of control and end points to draw to
  1109. @param y1 (number) y-coordinate of beginning control point (omitted if x1 is array)
  1110. @param x2 (number) x-coordinate of ending control point (omitted if x1 is array)
  1111. @param y2 (number) y-coordinate of ending control point (omitted if x1 is array)
  1112. @param x (number) x-coordinate of curve end (omitted if x1 is array)
  1113. @param y (number) y-coordinate of curve end (omitted if x1 is array)
  1114. @param relative (boolean) true for coordinates relative to the current point,
  1115. false for coordinates being absolute
  1116. @return (SVGPath) this path */
  1117. curveC: function(x1, y1, x2, y2, x, y, relative) {
  1118. relative = (isArray(x1) ? y1 : relative);
  1119. return this._coords((relative ? 'c' : 'C'), x1, y1, x2, y2, x, y);
  1120. },
  1121. /* Continue a cubic Bézier curve.
  1122. Starting control point is the reflection of the previous end control point.
  1123. @param x2 (number) x-coordinate of ending control point or
  1124. (number[][]) x-/y-coordinates of control and end points to draw to
  1125. @param y2 (number) y-coordinate of ending control point (omitted if x2 is array)
  1126. @param x (number) x-coordinate of curve end (omitted if x2 is array)
  1127. @param y (number) y-coordinate of curve end (omitted if x2 is array)
  1128. @param relative (boolean) true for coordinates relative to the current point,
  1129. false for coordinates being absolute
  1130. @return (SVGPath) this path */
  1131. smoothC: function(x2, y2, x, y, relative) {
  1132. relative = (isArray(x2) ? y2 : relative);
  1133. return this._coords((relative ? 's' : 'S'), x2, y2, x, y);
  1134. },
  1135. /* Draw a quadratic Bézier curve.
  1136. @param x1 (number) x-coordinate of control point or
  1137. (number[][]) x-/y-coordinates of control and end points to draw to
  1138. @param y1 (number) y-coordinate of control point (omitted if x1 is array)
  1139. @param x (number) x-coordinate of curve end (omitted if x1 is array)
  1140. @param y (number) y-coordinate of curve end (omitted if x1 is array)
  1141. @param relative (boolean) true for coordinates relative to the current point,
  1142. false for coordinates being absolute
  1143. @return (SVGPath) this path */
  1144. curveQ: function(x1, y1, x, y, relative) {
  1145. relative = (isArray(x1) ? y1 : relative);
  1146. return this._coords((relative ? 'q' : 'Q'), x1, y1, x, y);
  1147. },
  1148. /* Continue a quadratic Bézier curve.
  1149. Control point is the reflection of the previous control point.
  1150. @param x (number) x-coordinate of curve end or
  1151. (number[][]) x-/y-coordinates of points to draw to
  1152. @param y (number) y-coordinate of curve end (omitted if x is array)
  1153. @param relative (boolean) true for coordinates relative to the current point,
  1154. false for coordinates being absolute
  1155. @return (SVGPath) this path */
  1156. smoothQ: function(x, y, relative) {
  1157. relative = (isArray(x) ? y : relative);
  1158. return this._coords((relative ? 't' : 'T'), x, y);
  1159. },
  1160. /* Generate a path command with (a list of) coordinates. */
  1161. _coords: function(cmd, x1, y1, x2, y2, x3, y3) {
  1162. if (isArray(x1)) {
  1163. for (var i = 0; i < x1.length; i++) {
  1164. var cs = x1[i];
  1165. this._path += (i == 0 ? cmd : ' ') + cs[0] + ',' + cs[1] +
  1166. (cs.length < 4 ? '' : ' ' + cs[2] + ',' + cs[3] +
  1167. (cs.length < 6 ? '': ' ' + cs[4] + ',' + cs[5]));
  1168. }
  1169. }
  1170. else {
  1171. this._path += cmd + x1 + ',' + y1 +
  1172. (x2 == null ? '' : ' ' + x2 + ',' + y2 +
  1173. (x3 == null ? '' : ' ' + x3 + ',' + y3));
  1174. }
  1175. return this;
  1176. },
  1177. /* Draw an arc to a position.
  1178. @param rx (number) x-radius of arc or
  1179. (number/boolean[][]) x-/y-coordinates and flags for points to draw to
  1180. @param ry (number) y-radius of arc (omitted if rx is array)
  1181. @param xRotate (number) x-axis rotation (degrees, clockwise) (omitted if rx is array)
  1182. @param large (boolean) true to draw the large part of the arc,
  1183. false to draw the small part (omitted if rx is array)
  1184. @param clockwise (boolean) true to draw the clockwise arc,
  1185. false to draw the anti-clockwise arc (omitted if rx is array)
  1186. @param x (number) x-coordinate of arc end (omitted if rx is array)
  1187. @param y (number) y-coordinate of arc end (omitted if rx is array)
  1188. @param relative (boolean) true for coordinates relative to the current point,
  1189. false for coordinates being absolute
  1190. @return (SVGPath) this path */
  1191. arc: function(rx, ry, xRotate, large, clockwise, x, y, relative) {
  1192. relative = (isArray(rx) ? ry : relative);
  1193. this._path += (relative ? 'a' : 'A');
  1194. if (isArray(rx)) {
  1195. for (var i = 0; i < rx.length; i++) {
  1196. var cs = rx[i];
  1197. this._path += (i == 0 ? '' : ' ') + cs[0] + ',' + cs[1] + ' ' +
  1198. cs[2] + ' ' + (cs[3] ? '1' : '0') + ',' +
  1199. (cs[4] ? '1' : '0') + ' ' + cs[5] + ',' + cs[6];
  1200. }
  1201. }
  1202. else {
  1203. this._path += rx + ',' + ry + ' ' + xRotate + ' ' +
  1204. (large ? '1' : '0') + ',' + (clockwise ? '1' : '0') + ' ' + x + ',' + y;
  1205. }
  1206. return this;
  1207. },
  1208. /* Close the current path.
  1209. @return (SVGPath) this path */
  1210. close: function() {
  1211. this._path += 'z';
  1212. return this;
  1213. },
  1214. /* Return the string rendering of the specified path.
  1215. @return (string) stringified path */
  1216. path: function() {
  1217. return this._path;
  1218. }
  1219. });
  1220. SVGPath.prototype.moveTo = SVGPath.prototype.move;
  1221. SVGPath.prototype.lineTo = SVGPath.prototype.line;
  1222. SVGPath.prototype.horizTo = SVGPath.prototype.horiz;
  1223. SVGPath.prototype.vertTo = SVGPath.prototype.vert;
  1224. SVGPath.prototype.curveCTo = SVGPath.prototype.curveC;
  1225. SVGPath.prototype.smoothCTo = SVGPath.prototype.smoothC;
  1226. SVGPath.prototype.curveQTo = SVGPath.prototype.curveQ;
  1227. SVGPath.prototype.smoothQTo = SVGPath.prototype.smoothQ;
  1228. SVGPath.prototype.arcTo = SVGPath.prototype.arc;
  1229. /* Helper to generate an SVG text object.
  1230. Obtain an instance from the SVGWrapper object.
  1231. String calls together to generate the text and use its value:
  1232. var text = root.createText();
  1233. root.text(null, x, y, text.string('This is ').
  1234. span('red', {fill: 'red'}).string('!'), {fill: 'blue'}); */
  1235. function SVGText() {
  1236. this._parts = []; // The components of the text object
  1237. }
  1238. $.extend(SVGText.prototype, {
  1239. /* Prepare to create a new text object.
  1240. @return (SVGText) this text */
  1241. reset: function() {
  1242. this._parts = [];
  1243. return this;
  1244. },
  1245. /* Add a straight string value.
  1246. @param value (string) the actual text
  1247. @return (SVGText) this text object */
  1248. string: function(value) {
  1249. this._parts[this._parts.length] = ['text', value];
  1250. return this;
  1251. },
  1252. /* Add a separate text span that has its own settings.
  1253. @param value (string) the actual text
  1254. @param settings (object) the settings for this text
  1255. @return (SVGText) this text object */
  1256. span: function(value, settings) {
  1257. this._parts[this._parts.length] = ['tspan', value, settings];
  1258. return this;
  1259. },
  1260. /* Add a reference to a previously defined text string.
  1261. @param id (string) the ID of the actual text
  1262. @param settings (object) the settings for this text
  1263. @return (SVGText) this text object */
  1264. ref: function(id, settings) {
  1265. this._parts[this._parts.length] = ['tref', id, settings];
  1266. return this;
  1267. },
  1268. /* Add text drawn along a path.
  1269. @param id (string) the ID of the path
  1270. @param value (string) the actual text
  1271. @param settings (object) the settings for this text
  1272. @return (SVGText) this text object */
  1273. path: function(id, value, settings) {
  1274. this._parts[this._parts.length] = ['textpath', value,
  1275. $.extend({href: id}, settings || {})];
  1276. return this;
  1277. }
  1278. });
  1279. /* Attach the SVG functionality to a jQuery selection.
  1280. @param command (string) the command to run (optional, default 'attach')
  1281. @param options (object) the new settings to use for these SVG instances
  1282. @return jQuery (object) for chaining further calls */
  1283. $.fn.svg = function(options) {
  1284. var otherArgs = Array.prototype.slice.call(arguments, 1);
  1285. if (typeof options == 'string' && options == 'get') {
  1286. return $.svg['_' + options + 'SVG'].apply($.svg, [this[0]].concat(otherArgs));
  1287. }
  1288. return this.each(function() {
  1289. if (typeof options == 'string') {
  1290. $.svg['_' + options + 'SVG'].apply($.svg, [this].concat(otherArgs));
  1291. }
  1292. else {
  1293. $.svg._attachSVG(this, options || {});
  1294. }
  1295. });
  1296. };
  1297. /* Determine whether an object is an array. */
  1298. function isArray(a) {
  1299. return (a && a.constructor == Array);
  1300. }
  1301. // Singleton primary SVG interface
  1302. $.svg = new SVGManager();
  1303. })(jQuery);