canvas-tools.src.js 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164
  1. /**
  2. * @license A class to parse color values
  3. * @author Stoyan Stefanov <sstoo@gmail.com>
  4. * @link http://www.phpied.com/rgb-color-parser-in-javascript/
  5. * Use it if you like it
  6. *
  7. */
  8. function RGBColor(color_string) {
  9. this.ok = false;
  10. // strip any leading #
  11. if (color_string.charAt(0) == '#') { // remove # if any
  12. color_string = color_string.substr(1, 6);
  13. }
  14. color_string = color_string.replace(/ /g, '');
  15. color_string = color_string.toLowerCase();
  16. // before getting into regexps, try simple matches
  17. // and overwrite the input
  18. var simple_colors = {
  19. aliceblue: 'f0f8ff',
  20. antiquewhite: 'faebd7',
  21. aqua: '00ffff',
  22. aquamarine: '7fffd4',
  23. azure: 'f0ffff',
  24. beige: 'f5f5dc',
  25. bisque: 'ffe4c4',
  26. black: '000000',
  27. blanchedalmond: 'ffebcd',
  28. blue: '0000ff',
  29. blueviolet: '8a2be2',
  30. brown: 'a52a2a',
  31. burlywood: 'deb887',
  32. cadetblue: '5f9ea0',
  33. chartreuse: '7fff00',
  34. chocolate: 'd2691e',
  35. coral: 'ff7f50',
  36. cornflowerblue: '6495ed',
  37. cornsilk: 'fff8dc',
  38. crimson: 'dc143c',
  39. cyan: '00ffff',
  40. darkblue: '00008b',
  41. darkcyan: '008b8b',
  42. darkgoldenrod: 'b8860b',
  43. darkgray: 'a9a9a9',
  44. darkgreen: '006400',
  45. darkkhaki: 'bdb76b',
  46. darkmagenta: '8b008b',
  47. darkolivegreen: '556b2f',
  48. darkorange: 'ff8c00',
  49. darkorchid: '9932cc',
  50. darkred: '8b0000',
  51. darksalmon: 'e9967a',
  52. darkseagreen: '8fbc8f',
  53. darkslateblue: '483d8b',
  54. darkslategray: '2f4f4f',
  55. darkturquoise: '00ced1',
  56. darkviolet: '9400d3',
  57. deeppink: 'ff1493',
  58. deepskyblue: '00bfff',
  59. dimgray: '696969',
  60. dodgerblue: '1e90ff',
  61. feldspar: 'd19275',
  62. firebrick: 'b22222',
  63. floralwhite: 'fffaf0',
  64. forestgreen: '228b22',
  65. fuchsia: 'ff00ff',
  66. gainsboro: 'dcdcdc',
  67. ghostwhite: 'f8f8ff',
  68. gold: 'ffd700',
  69. goldenrod: 'daa520',
  70. gray: '808080',
  71. green: '008000',
  72. greenyellow: 'adff2f',
  73. honeydew: 'f0fff0',
  74. hotpink: 'ff69b4',
  75. indianred: 'cd5c5c',
  76. indigo: '4b0082',
  77. ivory: 'fffff0',
  78. khaki: 'f0e68c',
  79. lavender: 'e6e6fa',
  80. lavenderblush: 'fff0f5',
  81. lawngreen: '7cfc00',
  82. lemonchiffon: 'fffacd',
  83. lightblue: 'add8e6',
  84. lightcoral: 'f08080',
  85. lightcyan: 'e0ffff',
  86. lightgoldenrodyellow: 'fafad2',
  87. lightgrey: 'd3d3d3',
  88. lightgreen: '90ee90',
  89. lightpink: 'ffb6c1',
  90. lightsalmon: 'ffa07a',
  91. lightseagreen: '20b2aa',
  92. lightskyblue: '87cefa',
  93. lightslateblue: '8470ff',
  94. lightslategray: '778899',
  95. lightsteelblue: 'b0c4de',
  96. lightyellow: 'ffffe0',
  97. lime: '00ff00',
  98. limegreen: '32cd32',
  99. linen: 'faf0e6',
  100. magenta: 'ff00ff',
  101. maroon: '800000',
  102. mediumaquamarine: '66cdaa',
  103. mediumblue: '0000cd',
  104. mediumorchid: 'ba55d3',
  105. mediumpurple: '9370d8',
  106. mediumseagreen: '3cb371',
  107. mediumslateblue: '7b68ee',
  108. mediumspringgreen: '00fa9a',
  109. mediumturquoise: '48d1cc',
  110. mediumvioletred: 'c71585',
  111. midnightblue: '191970',
  112. mintcream: 'f5fffa',
  113. mistyrose: 'ffe4e1',
  114. moccasin: 'ffe4b5',
  115. navajowhite: 'ffdead',
  116. navy: '000080',
  117. oldlace: 'fdf5e6',
  118. olive: '808000',
  119. olivedrab: '6b8e23',
  120. orange: 'ffa500',
  121. orangered: 'ff4500',
  122. orchid: 'da70d6',
  123. palegoldenrod: 'eee8aa',
  124. palegreen: '98fb98',
  125. paleturquoise: 'afeeee',
  126. palevioletred: 'd87093',
  127. papayawhip: 'ffefd5',
  128. peachpuff: 'ffdab9',
  129. peru: 'cd853f',
  130. pink: 'ffc0cb',
  131. plum: 'dda0dd',
  132. powderblue: 'b0e0e6',
  133. purple: '800080',
  134. red: 'ff0000',
  135. rosybrown: 'bc8f8f',
  136. royalblue: '4169e1',
  137. saddlebrown: '8b4513',
  138. salmon: 'fa8072',
  139. sandybrown: 'f4a460',
  140. seagreen: '2e8b57',
  141. seashell: 'fff5ee',
  142. sienna: 'a0522d',
  143. silver: 'c0c0c0',
  144. skyblue: '87ceeb',
  145. slateblue: '6a5acd',
  146. slategray: '708090',
  147. snow: 'fffafa',
  148. springgreen: '00ff7f',
  149. steelblue: '4682b4',
  150. tan: 'd2b48c',
  151. teal: '008080',
  152. thistle: 'd8bfd8',
  153. tomato: 'ff6347',
  154. turquoise: '40e0d0',
  155. violet: 'ee82ee',
  156. violetred: 'd02090',
  157. wheat: 'f5deb3',
  158. white: 'ffffff',
  159. whitesmoke: 'f5f5f5',
  160. yellow: 'ffff00',
  161. yellowgreen: '9acd32'
  162. };
  163. for (var key in simple_colors) {
  164. if (color_string == key) {
  165. color_string = simple_colors[key];
  166. }
  167. }
  168. // emd of simple type-in colors
  169. // array of color definition objects
  170. var color_defs = [
  171. {
  172. re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
  173. example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
  174. process: function (bits) {
  175. return [
  176. parseInt(bits[1]),
  177. parseInt(bits[2]),
  178. parseInt(bits[3])
  179. ];
  180. }
  181. },
  182. {
  183. re: /^(\w{2})(\w{2})(\w{2})$/,
  184. example: ['#00ff00', '336699'],
  185. process: function (bits) {
  186. return [
  187. parseInt(bits[1], 16),
  188. parseInt(bits[2], 16),
  189. parseInt(bits[3], 16)
  190. ];
  191. }
  192. },
  193. {
  194. re: /^(\w{1})(\w{1})(\w{1})$/,
  195. example: ['#fb0', 'f0f'],
  196. process: function (bits) {
  197. return [
  198. parseInt(bits[1] + bits[1], 16),
  199. parseInt(bits[2] + bits[2], 16),
  200. parseInt(bits[3] + bits[3], 16)
  201. ];
  202. }
  203. }
  204. ];
  205. // search through the definitions to find a match
  206. for (var i = 0; i < color_defs.length; i++) {
  207. var re = color_defs[i].re;
  208. var processor = color_defs[i].process;
  209. var bits = re.exec(color_string);
  210. if (bits) {
  211. channels = processor(bits);
  212. this.r = channels[0];
  213. this.g = channels[1];
  214. this.b = channels[2];
  215. this.ok = true;
  216. }
  217. }
  218. // validate/cleanup values
  219. this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
  220. this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
  221. this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
  222. // some getters
  223. this.toRGB = function () {
  224. return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
  225. }
  226. this.toHex = function () {
  227. var r = this.r.toString(16);
  228. var g = this.g.toString(16);
  229. var b = this.b.toString(16);
  230. if (r.length == 1) r = '0' + r;
  231. if (g.length == 1) g = '0' + g;
  232. if (b.length == 1) b = '0' + b;
  233. return '#' + r + g + b;
  234. }
  235. // help
  236. this.getHelpXML = function () {
  237. var examples = new Array();
  238. // add regexps
  239. for (var i = 0; i < color_defs.length; i++) {
  240. var example = color_defs[i].example;
  241. for (var j = 0; j < example.length; j++) {
  242. examples[examples.length] = example[j];
  243. }
  244. }
  245. // add type-in colors
  246. for (var sc in simple_colors) {
  247. examples[examples.length] = sc;
  248. }
  249. var xml = document.createElement('ul');
  250. xml.setAttribute('id', 'rgbcolor-examples');
  251. for (var i = 0; i < examples.length; i++) {
  252. try {
  253. var list_item = document.createElement('li');
  254. var list_color = new RGBColor(examples[i]);
  255. var example_div = document.createElement('div');
  256. example_div.style.cssText =
  257. 'margin: 3px; '
  258. + 'border: 1px solid black; '
  259. + 'background:' + list_color.toHex() + '; '
  260. + 'color:' + list_color.toHex()
  261. ;
  262. example_div.appendChild(document.createTextNode('test'));
  263. var list_item_value = document.createTextNode(
  264. ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()
  265. );
  266. list_item.appendChild(example_div);
  267. list_item.appendChild(list_item_value);
  268. xml.appendChild(list_item);
  269. } catch (e) {
  270. }
  271. }
  272. return xml;
  273. }
  274. }
  275. /**
  276. * @license canvg.js - Javascript SVG parser and renderer on Canvas
  277. * MIT Licensed
  278. * Gabe Lerner (gabelerner@gmail.com)
  279. * http://code.google.com/p/canvg/
  280. *
  281. * Requires: rgbcolor.js - http://www.phpied.com/rgb-color-parser-in-javascript/
  282. *
  283. */
  284. if (!window.console) {
  285. window.console = {};
  286. window.console.log = function (str) {
  287. };
  288. window.console.dir = function (str) {
  289. };
  290. }
  291. if (!Array.prototype.indexOf) {
  292. Array.prototype.indexOf = function (obj) {
  293. for (var i = 0; i < this.length; i++) {
  294. if (this[i] == obj) {
  295. return i;
  296. }
  297. }
  298. return -1;
  299. }
  300. }
  301. (function () {
  302. // canvg(target, s)
  303. // empty parameters: replace all 'svg' elements on page with 'canvas' elements
  304. // target: canvas element or the id of a canvas element
  305. // s: svg string, url to svg file, or xml document
  306. // opts: optional hash of options
  307. // ignoreMouse: true => ignore mouse events
  308. // ignoreAnimation: true => ignore animations
  309. // ignoreDimensions: true => does not try to resize canvas
  310. // ignoreClear: true => does not clear canvas
  311. // offsetX: int => draws at a x offset
  312. // offsetY: int => draws at a y offset
  313. // scaleWidth: int => scales horizontally to width
  314. // scaleHeight: int => scales vertically to height
  315. // renderCallback: function => will call the function after the first render is completed
  316. // forceRedraw: function => will call the function on every frame, if it returns true, will redraw
  317. this.canvg = function (target, s, opts) {
  318. // no parameters
  319. if (target == null && s == null && opts == null) {
  320. var svgTags = document.getElementsByTagName('svg');
  321. for (var i = 0; i < svgTags.length; i++) {
  322. var svgTag = svgTags[i];
  323. var c = document.createElement('canvas');
  324. c.width = svgTag.clientWidth;
  325. c.height = svgTag.clientHeight;
  326. svgTag.parentNode.insertBefore(c, svgTag);
  327. svgTag.parentNode.removeChild(svgTag);
  328. var div = document.createElement('div');
  329. div.appendChild(svgTag);
  330. canvg(c, div.innerHTML);
  331. }
  332. return;
  333. }
  334. opts = opts || {};
  335. if (typeof target == 'string') {
  336. target = document.getElementById(target);
  337. }
  338. // reuse class per canvas
  339. var svg;
  340. if (target.svg == null) {
  341. svg = build();
  342. target.svg = svg;
  343. } else {
  344. svg = target.svg;
  345. svg.stop();
  346. }
  347. svg.opts = opts;
  348. var ctx = target.getContext('2d');
  349. if (typeof (s.documentElement) != 'undefined') {
  350. // load from xml doc
  351. svg.loadXmlDoc(ctx, s);
  352. } else if (s.substr(0, 1) == '<') {
  353. // load from xml string
  354. svg.loadXml(ctx, s);
  355. } else {
  356. // load from url
  357. svg.load(ctx, s);
  358. }
  359. }
  360. function build() {
  361. var svg = {};
  362. svg.FRAMERATE = 30;
  363. svg.MAX_VIRTUAL_PIXELS = 30000;
  364. // globals
  365. svg.init = function (ctx) {
  366. svg.Definitions = {};
  367. svg.Styles = {};
  368. svg.Animations = [];
  369. svg.Images = [];
  370. svg.ctx = ctx;
  371. svg.ViewPort = new (function () {
  372. this.viewPorts = [];
  373. this.Clear = function () {
  374. this.viewPorts = [];
  375. }
  376. this.SetCurrent = function (width, height) {
  377. this.viewPorts.push({width: width, height: height});
  378. }
  379. this.RemoveCurrent = function () {
  380. this.viewPorts.pop();
  381. }
  382. this.Current = function () {
  383. return this.viewPorts[this.viewPorts.length - 1];
  384. }
  385. this.width = function () {
  386. return this.Current().width;
  387. }
  388. this.height = function () {
  389. return this.Current().height;
  390. }
  391. this.ComputeSize = function (d) {
  392. if (d != null && typeof (d) == 'number') return d;
  393. if (d == 'x') return this.width();
  394. if (d == 'y') return this.height();
  395. return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2);
  396. }
  397. });
  398. }
  399. svg.init();
  400. // images loaded
  401. svg.ImagesLoaded = function () {
  402. for (var i = 0; i < svg.Images.length; i++) {
  403. if (!svg.Images[i].loaded) return false;
  404. }
  405. return true;
  406. }
  407. // trim
  408. svg.trim = function (s) {
  409. return s.replace(/^\s+|\s+$/g, '');
  410. }
  411. // compress spaces
  412. svg.compressSpaces = function (s) {
  413. return s.replace(/[\s\r\t\n]+/gm, ' ');
  414. }
  415. // ajax
  416. svg.ajax = function (url) {
  417. var AJAX;
  418. if (window.XMLHttpRequest) {
  419. AJAX = new XMLHttpRequest();
  420. } else {
  421. AJAX = new ActiveXObject('Microsoft.XMLHTTP');
  422. }
  423. if (AJAX) {
  424. AJAX.open('GET', url, false);
  425. AJAX.send(null);
  426. return AJAX.responseText;
  427. }
  428. return null;
  429. }
  430. // parse xml
  431. svg.parseXml = function (xml) {
  432. if (window.DOMParser) {
  433. var parser = new DOMParser();
  434. return parser.parseFromString(xml, 'text/xml');
  435. } else {
  436. xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
  437. var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
  438. xmlDoc.async = 'false';
  439. xmlDoc.loadXML(xml);
  440. return xmlDoc;
  441. }
  442. }
  443. svg.Property = function (name, value) {
  444. this.name = name;
  445. this.value = value;
  446. this.hasValue = function () {
  447. return (this.value != null && this.value !== '');
  448. }
  449. // return the numerical value of the property
  450. this.numValue = function () {
  451. if (!this.hasValue()) return 0;
  452. var n = parseFloat(this.value);
  453. if ((this.value + '').match(/%$/)) {
  454. n = n / 100.0;
  455. }
  456. return n;
  457. }
  458. this.valueOrDefault = function (def) {
  459. if (this.hasValue()) return this.value;
  460. return def;
  461. }
  462. this.numValueOrDefault = function (def) {
  463. if (this.hasValue()) return this.numValue();
  464. return def;
  465. }
  466. /* EXTENSIONS */
  467. var that = this;
  468. // color extensions
  469. this.Color = {
  470. // augment the current color value with the opacity
  471. addOpacity: function (opacity) {
  472. var newValue = that.value;
  473. if (opacity != null && opacity != '') {
  474. var color = new RGBColor(that.value);
  475. if (color.ok) {
  476. newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')';
  477. }
  478. }
  479. return new svg.Property(that.name, newValue);
  480. }
  481. }
  482. // definition extensions
  483. this.Definition = {
  484. // get the definition from the definitions table
  485. getDefinition: function () {
  486. var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2');
  487. return svg.Definitions[name];
  488. },
  489. isUrl: function () {
  490. return that.value.indexOf('url(') == 0
  491. },
  492. getFillStyle: function (e) {
  493. var def = this.getDefinition();
  494. // gradient
  495. if (def != null && def.createGradient) {
  496. return def.createGradient(svg.ctx, e);
  497. }
  498. // pattern
  499. if (def != null && def.createPattern) {
  500. return def.createPattern(svg.ctx, e);
  501. }
  502. return null;
  503. }
  504. }
  505. // length extensions
  506. this.Length = {
  507. DPI: function (viewPort) {
  508. return 96.0; // TODO: compute?
  509. },
  510. EM: function (viewPort) {
  511. var em = 12;
  512. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  513. if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort);
  514. return em;
  515. },
  516. // get the length as pixels
  517. toPixels: function (viewPort) {
  518. if (!that.hasValue()) return 0;
  519. var s = that.value + '';
  520. if (s.match(/em$/)) return that.numValue() * this.EM(viewPort);
  521. if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0;
  522. if (s.match(/px$/)) return that.numValue();
  523. if (s.match(/pt$/)) return that.numValue() * 1.25;
  524. if (s.match(/pc$/)) return that.numValue() * 15;
  525. if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54;
  526. if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4;
  527. if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort);
  528. if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort);
  529. return that.numValue();
  530. }
  531. }
  532. // time extensions
  533. this.Time = {
  534. // get the time as milliseconds
  535. toMilliseconds: function () {
  536. if (!that.hasValue()) return 0;
  537. var s = that.value + '';
  538. if (s.match(/s$/)) return that.numValue() * 1000;
  539. if (s.match(/ms$/)) return that.numValue();
  540. return that.numValue();
  541. }
  542. }
  543. // angle extensions
  544. this.Angle = {
  545. // get the angle as radians
  546. toRadians: function () {
  547. if (!that.hasValue()) return 0;
  548. var s = that.value + '';
  549. if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0);
  550. if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0);
  551. if (s.match(/rad$/)) return that.numValue();
  552. return that.numValue() * (Math.PI / 180.0);
  553. }
  554. }
  555. }
  556. // fonts
  557. svg.Font = new (function () {
  558. this.Styles = ['normal', 'italic', 'oblique', 'inherit'];
  559. this.Variants = ['normal', 'small-caps', 'inherit'];
  560. this.Weights = ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'inherit'];
  561. this.CreateFont = function (fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) {
  562. var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font);
  563. return {
  564. fontFamily: fontFamily || f.fontFamily,
  565. fontSize: fontSize || f.fontSize,
  566. fontStyle: fontStyle || f.fontStyle,
  567. fontWeight: fontWeight || f.fontWeight,
  568. fontVariant: fontVariant || f.fontVariant,
  569. toString: function () {
  570. return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ')
  571. }
  572. }
  573. }
  574. var that = this;
  575. this.Parse = function (s) {
  576. var f = {};
  577. var d = svg.trim(svg.compressSpaces(s || '')).split(' ');
  578. var set = {fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false}
  579. var ff = '';
  580. for (var i = 0; i < d.length; i++) {
  581. if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) {
  582. if (d[i] != 'inherit') f.fontStyle = d[i];
  583. set.fontStyle = true;
  584. } else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) {
  585. if (d[i] != 'inherit') f.fontVariant = d[i];
  586. set.fontStyle = set.fontVariant = true;
  587. } else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) {
  588. if (d[i] != 'inherit') f.fontWeight = d[i];
  589. set.fontStyle = set.fontVariant = set.fontWeight = true;
  590. } else if (!set.fontSize) {
  591. if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0];
  592. set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true;
  593. } else {
  594. if (d[i] != 'inherit') ff += d[i];
  595. }
  596. }
  597. if (ff != '') f.fontFamily = ff;
  598. return f;
  599. }
  600. });
  601. // points and paths
  602. svg.ToNumberArray = function (s) {
  603. var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' ');
  604. for (var i = 0; i < a.length; i++) {
  605. a[i] = parseFloat(a[i]);
  606. }
  607. return a;
  608. }
  609. svg.Point = function (x, y) {
  610. this.x = x;
  611. this.y = y;
  612. this.angleTo = function (p) {
  613. return Math.atan2(p.y - this.y, p.x - this.x);
  614. }
  615. this.applyTransform = function (v) {
  616. var xp = this.x * v[0] + this.y * v[2] + v[4];
  617. var yp = this.x * v[1] + this.y * v[3] + v[5];
  618. this.x = xp;
  619. this.y = yp;
  620. }
  621. }
  622. svg.CreatePoint = function (s) {
  623. var a = svg.ToNumberArray(s);
  624. return new svg.Point(a[0], a[1]);
  625. }
  626. svg.CreatePath = function (s) {
  627. var a = svg.ToNumberArray(s);
  628. var path = [];
  629. for (var i = 0; i < a.length; i += 2) {
  630. path.push(new svg.Point(a[i], a[i + 1]));
  631. }
  632. return path;
  633. }
  634. // bounding box
  635. svg.BoundingBox = function (x1, y1, x2, y2) { // pass in initial points if you want
  636. this.x1 = Number.NaN;
  637. this.y1 = Number.NaN;
  638. this.x2 = Number.NaN;
  639. this.y2 = Number.NaN;
  640. this.x = function () {
  641. return this.x1;
  642. }
  643. this.y = function () {
  644. return this.y1;
  645. }
  646. this.width = function () {
  647. return this.x2 - this.x1;
  648. }
  649. this.height = function () {
  650. return this.y2 - this.y1;
  651. }
  652. this.addPoint = function (x, y) {
  653. if (x != null) {
  654. if (isNaN(this.x1) || isNaN(this.x2)) {
  655. this.x1 = x;
  656. this.x2 = x;
  657. }
  658. if (x < this.x1) this.x1 = x;
  659. if (x > this.x2) this.x2 = x;
  660. }
  661. if (y != null) {
  662. if (isNaN(this.y1) || isNaN(this.y2)) {
  663. this.y1 = y;
  664. this.y2 = y;
  665. }
  666. if (y < this.y1) this.y1 = y;
  667. if (y > this.y2) this.y2 = y;
  668. }
  669. }
  670. this.addX = function (x) {
  671. this.addPoint(x, null);
  672. }
  673. this.addY = function (y) {
  674. this.addPoint(null, y);
  675. }
  676. this.addBoundingBox = function (bb) {
  677. this.addPoint(bb.x1, bb.y1);
  678. this.addPoint(bb.x2, bb.y2);
  679. }
  680. this.addQuadraticCurve = function (p0x, p0y, p1x, p1y, p2x, p2y) {
  681. var cp1x = p0x + 2 / 3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0)
  682. var cp1y = p0y + 2 / 3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0)
  683. var cp2x = cp1x + 1 / 3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0)
  684. var cp2y = cp1y + 1 / 3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0)
  685. this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y);
  686. }
  687. this.addBezierCurve = function (p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
  688. // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
  689. var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y];
  690. this.addPoint(p0[0], p0[1]);
  691. this.addPoint(p3[0], p3[1]);
  692. for (i = 0; i <= 1; i++) {
  693. var f = function (t) {
  694. return Math.pow(1 - t, 3) * p0[i]
  695. + 3 * Math.pow(1 - t, 2) * t * p1[i]
  696. + 3 * (1 - t) * Math.pow(t, 2) * p2[i]
  697. + Math.pow(t, 3) * p3[i];
  698. }
  699. var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
  700. var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
  701. var c = 3 * p1[i] - 3 * p0[i];
  702. if (a == 0) {
  703. if (b == 0) continue;
  704. var t = -c / b;
  705. if (0 < t && t < 1) {
  706. if (i == 0) this.addX(f(t));
  707. if (i == 1) this.addY(f(t));
  708. }
  709. continue;
  710. }
  711. var b2ac = Math.pow(b, 2) - 4 * c * a;
  712. if (b2ac < 0) continue;
  713. var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
  714. if (0 < t1 && t1 < 1) {
  715. if (i == 0) this.addX(f(t1));
  716. if (i == 1) this.addY(f(t1));
  717. }
  718. var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
  719. if (0 < t2 && t2 < 1) {
  720. if (i == 0) this.addX(f(t2));
  721. if (i == 1) this.addY(f(t2));
  722. }
  723. }
  724. }
  725. this.isPointInBox = function (x, y) {
  726. return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2);
  727. }
  728. this.addPoint(x1, y1);
  729. this.addPoint(x2, y2);
  730. }
  731. // transforms
  732. svg.Transform = function (v) {
  733. var that = this;
  734. this.Type = {}
  735. // translate
  736. this.Type.translate = function (s) {
  737. this.p = svg.CreatePoint(s);
  738. this.apply = function (ctx) {
  739. ctx.translate(this.p.x || 0.0, this.p.y || 0.0);
  740. }
  741. this.applyToPoint = function (p) {
  742. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  743. }
  744. }
  745. // rotate
  746. this.Type.rotate = function (s) {
  747. var a = svg.ToNumberArray(s);
  748. this.angle = new svg.Property('angle', a[0]);
  749. this.cx = a[1] || 0;
  750. this.cy = a[2] || 0;
  751. this.apply = function (ctx) {
  752. ctx.translate(this.cx, this.cy);
  753. ctx.rotate(this.angle.Angle.toRadians());
  754. ctx.translate(-this.cx, -this.cy);
  755. }
  756. this.applyToPoint = function (p) {
  757. var a = this.angle.Angle.toRadians();
  758. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  759. p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]);
  760. p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]);
  761. }
  762. }
  763. this.Type.scale = function (s) {
  764. this.p = svg.CreatePoint(s);
  765. this.apply = function (ctx) {
  766. ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0);
  767. }
  768. this.applyToPoint = function (p) {
  769. p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]);
  770. }
  771. }
  772. this.Type.matrix = function (s) {
  773. this.m = svg.ToNumberArray(s);
  774. this.apply = function (ctx) {
  775. ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
  776. }
  777. this.applyToPoint = function (p) {
  778. p.applyTransform(this.m);
  779. }
  780. }
  781. this.Type.SkewBase = function (s) {
  782. this.base = that.Type.matrix;
  783. this.base(s);
  784. this.angle = new svg.Property('angle', s);
  785. }
  786. this.Type.SkewBase.prototype = new this.Type.matrix;
  787. this.Type.skewX = function (s) {
  788. this.base = that.Type.SkewBase;
  789. this.base(s);
  790. this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0];
  791. }
  792. this.Type.skewX.prototype = new this.Type.SkewBase;
  793. this.Type.skewY = function (s) {
  794. this.base = that.Type.SkewBase;
  795. this.base(s);
  796. this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0];
  797. }
  798. this.Type.skewY.prototype = new this.Type.SkewBase;
  799. this.transforms = [];
  800. this.apply = function (ctx) {
  801. for (var i = 0; i < this.transforms.length; i++) {
  802. this.transforms[i].apply(ctx);
  803. }
  804. }
  805. this.applyToPoint = function (p) {
  806. for (var i = 0; i < this.transforms.length; i++) {
  807. this.transforms[i].applyToPoint(p);
  808. }
  809. }
  810. var data = svg.trim(svg.compressSpaces(v)).split(/\s(?=[a-z])/);
  811. for (var i = 0; i < data.length; i++) {
  812. var type = data[i].split('(')[0];
  813. var s = data[i].split('(')[1].replace(')', '');
  814. var transform = new this.Type[type](s);
  815. this.transforms.push(transform);
  816. }
  817. }
  818. // aspect ratio
  819. svg.AspectRatio = function (ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {
  820. // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
  821. aspectRatio = svg.compressSpaces(aspectRatio);
  822. aspectRatio = aspectRatio.replace(/^defer\s/, ''); // ignore defer
  823. var align = aspectRatio.split(' ')[0] || 'xMidYMid';
  824. var meetOrSlice = aspectRatio.split(' ')[1] || 'meet';
  825. // calculate scale
  826. var scaleX = width / desiredWidth;
  827. var scaleY = height / desiredHeight;
  828. var scaleMin = Math.min(scaleX, scaleY);
  829. var scaleMax = Math.max(scaleX, scaleY);
  830. if (meetOrSlice == 'meet') {
  831. desiredWidth *= scaleMin;
  832. desiredHeight *= scaleMin;
  833. }
  834. if (meetOrSlice == 'slice') {
  835. desiredWidth *= scaleMax;
  836. desiredHeight *= scaleMax;
  837. }
  838. refX = new svg.Property('refX', refX);
  839. refY = new svg.Property('refY', refY);
  840. if (refX.hasValue() && refY.hasValue()) {
  841. ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y'));
  842. } else {
  843. // align
  844. if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);
  845. if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);
  846. if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0);
  847. if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight);
  848. }
  849. // scale
  850. if (align == 'none') ctx.scale(scaleX, scaleY);
  851. else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin);
  852. else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax);
  853. // translate
  854. ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);
  855. }
  856. // elements
  857. svg.Element = {}
  858. svg.Element.ElementBase = function (node) {
  859. this.attributes = {};
  860. this.styles = {};
  861. this.children = [];
  862. // get or create attribute
  863. this.attribute = function (name, createIfNotExists) {
  864. var a = this.attributes[name];
  865. if (a != null) return a;
  866. a = new svg.Property(name, '');
  867. if (createIfNotExists == true) this.attributes[name] = a;
  868. return a;
  869. }
  870. // get or create style, crawls up node tree
  871. this.style = function (name, createIfNotExists) {
  872. var s = this.styles[name];
  873. if (s != null) return s;
  874. var a = this.attribute(name);
  875. if (a != null && a.hasValue()) {
  876. return a;
  877. }
  878. var p = this.parent;
  879. if (p != null) {
  880. var ps = p.style(name);
  881. if (ps != null && ps.hasValue()) {
  882. return ps;
  883. }
  884. }
  885. s = new svg.Property(name, '');
  886. if (createIfNotExists == true) this.styles[name] = s;
  887. return s;
  888. }
  889. // base render
  890. this.render = function (ctx) {
  891. // don't render display=none
  892. if (this.style('display').value == 'none') return;
  893. // don't render visibility=hidden
  894. if (this.attribute('visibility').value == 'hidden') return;
  895. ctx.save();
  896. this.setContext(ctx);
  897. // mask
  898. if (this.attribute('mask').hasValue()) {
  899. var mask = this.attribute('mask').Definition.getDefinition();
  900. if (mask != null) mask.apply(ctx, this);
  901. } else if (this.style('filter').hasValue()) {
  902. var filter = this.style('filter').Definition.getDefinition();
  903. if (filter != null) filter.apply(ctx, this);
  904. } else this.renderChildren(ctx);
  905. this.clearContext(ctx);
  906. ctx.restore();
  907. }
  908. // base set context
  909. this.setContext = function (ctx) {
  910. // OVERRIDE ME!
  911. }
  912. // base clear context
  913. this.clearContext = function (ctx) {
  914. // OVERRIDE ME!
  915. }
  916. // base render children
  917. this.renderChildren = function (ctx) {
  918. for (var i = 0; i < this.children.length; i++) {
  919. this.children[i].render(ctx);
  920. }
  921. }
  922. this.addChild = function (childNode, create) {
  923. var child = childNode;
  924. if (create) child = svg.CreateElement(childNode);
  925. child.parent = this;
  926. this.children.push(child);
  927. }
  928. if (node != null && node.nodeType == 1) { //ELEMENT_NODE
  929. // add children
  930. for (var i = 0; i < node.childNodes.length; i++) {
  931. var childNode = node.childNodes[i];
  932. if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE
  933. }
  934. // add attributes
  935. for (var i = 0; i < node.attributes.length; i++) {
  936. var attribute = node.attributes[i];
  937. this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue);
  938. }
  939. // add tag styles
  940. var styles = svg.Styles[node.nodeName];
  941. if (styles != null) {
  942. for (var name in styles) {
  943. this.styles[name] = styles[name];
  944. }
  945. }
  946. // add class styles
  947. if (this.attribute('class').hasValue()) {
  948. var classes = svg.compressSpaces(this.attribute('class').value).split(' ');
  949. for (var j = 0; j < classes.length; j++) {
  950. styles = svg.Styles['.' + classes[j]];
  951. if (styles != null) {
  952. for (var name in styles) {
  953. this.styles[name] = styles[name];
  954. }
  955. }
  956. styles = svg.Styles[node.nodeName + '.' + classes[j]];
  957. if (styles != null) {
  958. for (var name in styles) {
  959. this.styles[name] = styles[name];
  960. }
  961. }
  962. }
  963. }
  964. // add inline styles
  965. if (this.attribute('style').hasValue()) {
  966. var styles = this.attribute('style').value.split(';');
  967. for (var i = 0; i < styles.length; i++) {
  968. if (svg.trim(styles[i]) != '') {
  969. var style = styles[i].split(':');
  970. var name = svg.trim(style[0]);
  971. var value = svg.trim(style[1]);
  972. this.styles[name] = new svg.Property(name, value);
  973. }
  974. }
  975. }
  976. // add id
  977. if (this.attribute('id').hasValue()) {
  978. if (svg.Definitions[this.attribute('id').value] == null) {
  979. svg.Definitions[this.attribute('id').value] = this;
  980. }
  981. }
  982. }
  983. }
  984. svg.Element.RenderedElementBase = function (node) {
  985. this.base = svg.Element.ElementBase;
  986. this.base(node);
  987. this.setContext = function (ctx) {
  988. // fill
  989. if (this.style('fill').Definition.isUrl()) {
  990. var fs = this.style('fill').Definition.getFillStyle(this);
  991. if (fs != null) ctx.fillStyle = fs;
  992. } else if (this.style('fill').hasValue()) {
  993. var fillStyle = this.style('fill');
  994. if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value);
  995. ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);
  996. }
  997. // stroke
  998. if (this.style('stroke').Definition.isUrl()) {
  999. var fs = this.style('stroke').Definition.getFillStyle(this);
  1000. if (fs != null) ctx.strokeStyle = fs;
  1001. } else if (this.style('stroke').hasValue()) {
  1002. var strokeStyle = this.style('stroke');
  1003. if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value);
  1004. ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);
  1005. }
  1006. if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels();
  1007. if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;
  1008. if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;
  1009. if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;
  1010. // font
  1011. if (typeof (ctx.font) != 'undefined') {
  1012. ctx.font = svg.Font.CreateFont(
  1013. this.style('font-style').value,
  1014. this.style('font-variant').value,
  1015. this.style('font-weight').value,
  1016. this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '',
  1017. this.style('font-family').value).toString();
  1018. }
  1019. // transform
  1020. if (this.attribute('transform').hasValue()) {
  1021. var transform = new svg.Transform(this.attribute('transform').value);
  1022. transform.apply(ctx);
  1023. }
  1024. // clip
  1025. if (this.attribute('clip-path').hasValue()) {
  1026. var clip = this.attribute('clip-path').Definition.getDefinition();
  1027. if (clip != null) clip.apply(ctx);
  1028. }
  1029. // opacity
  1030. if (this.style('opacity').hasValue()) {
  1031. ctx.globalAlpha = this.style('opacity').numValue();
  1032. }
  1033. }
  1034. }
  1035. svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase;
  1036. svg.Element.PathElementBase = function (node) {
  1037. this.base = svg.Element.RenderedElementBase;
  1038. this.base(node);
  1039. this.path = function (ctx) {
  1040. if (ctx != null) ctx.beginPath();
  1041. return new svg.BoundingBox();
  1042. }
  1043. this.renderChildren = function (ctx) {
  1044. this.path(ctx);
  1045. svg.Mouse.checkPath(this, ctx);
  1046. if (ctx.fillStyle != '') ctx.fill();
  1047. if (ctx.strokeStyle != '') ctx.stroke();
  1048. var markers = this.getMarkers();
  1049. if (markers != null) {
  1050. if (this.style('marker-start').Definition.isUrl()) {
  1051. var marker = this.style('marker-start').Definition.getDefinition();
  1052. marker.render(ctx, markers[0][0], markers[0][1]);
  1053. }
  1054. if (this.style('marker-mid').Definition.isUrl()) {
  1055. var marker = this.style('marker-mid').Definition.getDefinition();
  1056. for (var i = 1; i < markers.length - 1; i++) {
  1057. marker.render(ctx, markers[i][0], markers[i][1]);
  1058. }
  1059. }
  1060. if (this.style('marker-end').Definition.isUrl()) {
  1061. var marker = this.style('marker-end').Definition.getDefinition();
  1062. marker.render(ctx, markers[markers.length - 1][0], markers[markers.length - 1][1]);
  1063. }
  1064. }
  1065. }
  1066. this.getBoundingBox = function () {
  1067. return this.path();
  1068. }
  1069. this.getMarkers = function () {
  1070. return null;
  1071. }
  1072. }
  1073. svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase;
  1074. // svg element
  1075. svg.Element.svg = function (node) {
  1076. this.base = svg.Element.RenderedElementBase;
  1077. this.base(node);
  1078. this.baseClearContext = this.clearContext;
  1079. this.clearContext = function (ctx) {
  1080. this.baseClearContext(ctx);
  1081. svg.ViewPort.RemoveCurrent();
  1082. }
  1083. this.baseSetContext = this.setContext;
  1084. this.setContext = function (ctx) {
  1085. // initial values
  1086. ctx.strokeStyle = 'rgba(0,0,0,0)';
  1087. ctx.lineCap = 'butt';
  1088. ctx.lineJoin = 'miter';
  1089. ctx.miterLimit = 4;
  1090. this.baseSetContext(ctx);
  1091. // create new view port
  1092. if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {
  1093. ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y'));
  1094. }
  1095. var width = svg.ViewPort.width();
  1096. var height = svg.ViewPort.height();
  1097. if (typeof (this.root) == 'undefined' && this.attribute('width').hasValue() && this.attribute('height').hasValue()) {
  1098. width = this.attribute('width').Length.toPixels('x');
  1099. height = this.attribute('height').Length.toPixels('y');
  1100. var x = 0;
  1101. var y = 0;
  1102. if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {
  1103. x = -this.attribute('refX').Length.toPixels('x');
  1104. y = -this.attribute('refY').Length.toPixels('y');
  1105. }
  1106. ctx.beginPath();
  1107. ctx.moveTo(x, y);
  1108. ctx.lineTo(width, y);
  1109. ctx.lineTo(width, height);
  1110. ctx.lineTo(x, height);
  1111. ctx.closePath();
  1112. ctx.clip();
  1113. }
  1114. svg.ViewPort.SetCurrent(width, height);
  1115. // viewbox
  1116. if (this.attribute('viewBox').hasValue()) {
  1117. var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
  1118. var minX = viewBox[0];
  1119. var minY = viewBox[1];
  1120. width = viewBox[2];
  1121. height = viewBox[3];
  1122. svg.AspectRatio(ctx,
  1123. this.attribute('preserveAspectRatio').value,
  1124. svg.ViewPort.width(),
  1125. width,
  1126. svg.ViewPort.height(),
  1127. height,
  1128. minX,
  1129. minY,
  1130. this.attribute('refX').value,
  1131. this.attribute('refY').value);
  1132. svg.ViewPort.RemoveCurrent();
  1133. svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
  1134. }
  1135. }
  1136. }
  1137. svg.Element.svg.prototype = new svg.Element.RenderedElementBase;
  1138. // rect element
  1139. svg.Element.rect = function (node) {
  1140. this.base = svg.Element.PathElementBase;
  1141. this.base(node);
  1142. this.path = function (ctx) {
  1143. var x = this.attribute('x').Length.toPixels('x');
  1144. var y = this.attribute('y').Length.toPixels('y');
  1145. var width = this.attribute('width').Length.toPixels('x');
  1146. var height = this.attribute('height').Length.toPixels('y');
  1147. var rx = this.attribute('rx').Length.toPixels('x');
  1148. var ry = this.attribute('ry').Length.toPixels('y');
  1149. if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;
  1150. if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;
  1151. if (ctx != null) {
  1152. ctx.beginPath();
  1153. ctx.moveTo(x + rx, y);
  1154. ctx.lineTo(x + width - rx, y);
  1155. ctx.quadraticCurveTo(x + width, y, x + width, y + ry)
  1156. ctx.lineTo(x + width, y + height - ry);
  1157. ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height)
  1158. ctx.lineTo(x + rx, y + height);
  1159. ctx.quadraticCurveTo(x, y + height, x, y + height - ry)
  1160. ctx.lineTo(x, y + ry);
  1161. ctx.quadraticCurveTo(x, y, x + rx, y)
  1162. ctx.closePath();
  1163. }
  1164. return new svg.BoundingBox(x, y, x + width, y + height);
  1165. }
  1166. }
  1167. svg.Element.rect.prototype = new svg.Element.PathElementBase;
  1168. // circle element
  1169. svg.Element.circle = function (node) {
  1170. this.base = svg.Element.PathElementBase;
  1171. this.base(node);
  1172. this.path = function (ctx) {
  1173. var cx = this.attribute('cx').Length.toPixels('x');
  1174. var cy = this.attribute('cy').Length.toPixels('y');
  1175. var r = this.attribute('r').Length.toPixels();
  1176. if (ctx != null) {
  1177. ctx.beginPath();
  1178. ctx.arc(cx, cy, r, 0, Math.PI * 2, true);
  1179. ctx.closePath();
  1180. }
  1181. return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);
  1182. }
  1183. }
  1184. svg.Element.circle.prototype = new svg.Element.PathElementBase;
  1185. // ellipse element
  1186. svg.Element.ellipse = function (node) {
  1187. this.base = svg.Element.PathElementBase;
  1188. this.base(node);
  1189. this.path = function (ctx) {
  1190. var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
  1191. var rx = this.attribute('rx').Length.toPixels('x');
  1192. var ry = this.attribute('ry').Length.toPixels('y');
  1193. var cx = this.attribute('cx').Length.toPixels('x');
  1194. var cy = this.attribute('cy').Length.toPixels('y');
  1195. if (ctx != null) {
  1196. ctx.beginPath();
  1197. ctx.moveTo(cx, cy - ry);
  1198. ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);
  1199. ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);
  1200. ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);
  1201. ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);
  1202. ctx.closePath();
  1203. }
  1204. return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);
  1205. }
  1206. }
  1207. svg.Element.ellipse.prototype = new svg.Element.PathElementBase;
  1208. // line element
  1209. svg.Element.line = function (node) {
  1210. this.base = svg.Element.PathElementBase;
  1211. this.base(node);
  1212. this.getPoints = function () {
  1213. return [
  1214. new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')),
  1215. new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))];
  1216. }
  1217. this.path = function (ctx) {
  1218. var points = this.getPoints();
  1219. if (ctx != null) {
  1220. ctx.beginPath();
  1221. ctx.moveTo(points[0].x, points[0].y);
  1222. ctx.lineTo(points[1].x, points[1].y);
  1223. }
  1224. return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);
  1225. }
  1226. this.getMarkers = function () {
  1227. var points = this.getPoints();
  1228. var a = points[0].angleTo(points[1]);
  1229. return [[points[0], a], [points[1], a]];
  1230. }
  1231. }
  1232. svg.Element.line.prototype = new svg.Element.PathElementBase;
  1233. // polyline element
  1234. svg.Element.polyline = function (node) {
  1235. this.base = svg.Element.PathElementBase;
  1236. this.base(node);
  1237. this.points = svg.CreatePath(this.attribute('points').value);
  1238. this.path = function (ctx) {
  1239. var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);
  1240. if (ctx != null) {
  1241. ctx.beginPath();
  1242. ctx.moveTo(this.points[0].x, this.points[0].y);
  1243. }
  1244. for (var i = 1; i < this.points.length; i++) {
  1245. bb.addPoint(this.points[i].x, this.points[i].y);
  1246. if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);
  1247. }
  1248. return bb;
  1249. }
  1250. this.getMarkers = function () {
  1251. var markers = [];
  1252. for (var i = 0; i < this.points.length - 1; i++) {
  1253. markers.push([this.points[i], this.points[i].angleTo(this.points[i + 1])]);
  1254. }
  1255. markers.push([this.points[this.points.length - 1], markers[markers.length - 1][1]]);
  1256. return markers;
  1257. }
  1258. }
  1259. svg.Element.polyline.prototype = new svg.Element.PathElementBase;
  1260. // polygon element
  1261. svg.Element.polygon = function (node) {
  1262. this.base = svg.Element.polyline;
  1263. this.base(node);
  1264. this.basePath = this.path;
  1265. this.path = function (ctx) {
  1266. var bb = this.basePath(ctx);
  1267. if (ctx != null) {
  1268. ctx.lineTo(this.points[0].x, this.points[0].y);
  1269. ctx.closePath();
  1270. }
  1271. return bb;
  1272. }
  1273. }
  1274. svg.Element.polygon.prototype = new svg.Element.polyline;
  1275. // path element
  1276. svg.Element.path = function (node) {
  1277. this.base = svg.Element.PathElementBase;
  1278. this.base(node);
  1279. var d = this.attribute('d').value;
  1280. // TODO: convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF
  1281. d = d.replace(/,/gm, ' '); // get rid of all commas
  1282. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2'); // separate commands from commands
  1283. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2'); // separate commands from commands
  1284. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm, '$1 $2'); // separate commands from points
  1285. d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2'); // separate commands from points
  1286. d = d.replace(/([0-9])([+\-])/gm, '$1 $2'); // separate digits when no comma
  1287. d = d.replace(/(\.[0-9]*)(\.)/gm, '$1 $2'); // separate digits when no comma
  1288. d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm, '$1 $3 $4 '); // shorthand elliptical arc path syntax
  1289. d = svg.compressSpaces(d); // compress multiple spaces
  1290. d = svg.trim(d);
  1291. this.PathParser = new (function (d) {
  1292. this.tokens = d.split(' ');
  1293. this.reset = function () {
  1294. this.i = -1;
  1295. this.command = '';
  1296. this.previousCommand = '';
  1297. this.start = new svg.Point(0, 0);
  1298. this.control = new svg.Point(0, 0);
  1299. this.current = new svg.Point(0, 0);
  1300. this.points = [];
  1301. this.angles = [];
  1302. }
  1303. this.isEnd = function () {
  1304. return this.i >= this.tokens.length - 1;
  1305. }
  1306. this.isCommandOrEnd = function () {
  1307. if (this.isEnd()) return true;
  1308. return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null;
  1309. }
  1310. this.isRelativeCommand = function () {
  1311. return this.command == this.command.toLowerCase();
  1312. }
  1313. this.getToken = function () {
  1314. this.i = this.i + 1;
  1315. return this.tokens[this.i];
  1316. }
  1317. this.getScalar = function () {
  1318. return parseFloat(this.getToken());
  1319. }
  1320. this.nextCommand = function () {
  1321. this.previousCommand = this.command;
  1322. this.command = this.getToken();
  1323. }
  1324. this.getPoint = function () {
  1325. var p = new svg.Point(this.getScalar(), this.getScalar());
  1326. return this.makeAbsolute(p);
  1327. }
  1328. this.getAsControlPoint = function () {
  1329. var p = this.getPoint();
  1330. this.control = p;
  1331. return p;
  1332. }
  1333. this.getAsCurrentPoint = function () {
  1334. var p = this.getPoint();
  1335. this.current = p;
  1336. return p;
  1337. }
  1338. this.getReflectedControlPoint = function () {
  1339. if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') {
  1340. return this.current;
  1341. }
  1342. // reflect point
  1343. var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);
  1344. return p;
  1345. }
  1346. this.makeAbsolute = function (p) {
  1347. if (this.isRelativeCommand()) {
  1348. p.x = this.current.x + p.x;
  1349. p.y = this.current.y + p.y;
  1350. }
  1351. return p;
  1352. }
  1353. this.addMarker = function (p, from, priorTo) {
  1354. // if the last angle isn't filled in because we didn't have this point yet ...
  1355. if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length - 1] == null) {
  1356. this.angles[this.angles.length - 1] = this.points[this.points.length - 1].angleTo(priorTo);
  1357. }
  1358. this.addMarkerAngle(p, from == null ? null : from.angleTo(p));
  1359. }
  1360. this.addMarkerAngle = function (p, a) {
  1361. this.points.push(p);
  1362. this.angles.push(a);
  1363. }
  1364. this.getMarkerPoints = function () {
  1365. return this.points;
  1366. }
  1367. this.getMarkerAngles = function () {
  1368. for (var i = 0; i < this.angles.length; i++) {
  1369. if (this.angles[i] == null) {
  1370. for (var j = i + 1; j < this.angles.length; j++) {
  1371. if (this.angles[j] != null) {
  1372. this.angles[i] = this.angles[j];
  1373. break;
  1374. }
  1375. }
  1376. }
  1377. }
  1378. return this.angles;
  1379. }
  1380. })(d);
  1381. this.path = function (ctx) {
  1382. var pp = this.PathParser;
  1383. pp.reset();
  1384. var bb = new svg.BoundingBox();
  1385. if (ctx != null) ctx.beginPath();
  1386. while (!pp.isEnd()) {
  1387. pp.nextCommand();
  1388. switch (pp.command.toUpperCase()) {
  1389. case 'M':
  1390. var p = pp.getAsCurrentPoint();
  1391. pp.addMarker(p);
  1392. bb.addPoint(p.x, p.y);
  1393. if (ctx != null) ctx.moveTo(p.x, p.y);
  1394. pp.start = pp.current;
  1395. while (!pp.isCommandOrEnd()) {
  1396. var p = pp.getAsCurrentPoint();
  1397. pp.addMarker(p, pp.start);
  1398. bb.addPoint(p.x, p.y);
  1399. if (ctx != null) ctx.lineTo(p.x, p.y);
  1400. }
  1401. break;
  1402. case 'L':
  1403. while (!pp.isCommandOrEnd()) {
  1404. var c = pp.current;
  1405. var p = pp.getAsCurrentPoint();
  1406. pp.addMarker(p, c);
  1407. bb.addPoint(p.x, p.y);
  1408. if (ctx != null) ctx.lineTo(p.x, p.y);
  1409. }
  1410. break;
  1411. case 'H':
  1412. while (!pp.isCommandOrEnd()) {
  1413. var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);
  1414. pp.addMarker(newP, pp.current);
  1415. pp.current = newP;
  1416. bb.addPoint(pp.current.x, pp.current.y);
  1417. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1418. }
  1419. break;
  1420. case 'V':
  1421. while (!pp.isCommandOrEnd()) {
  1422. var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
  1423. pp.addMarker(newP, pp.current);
  1424. pp.current = newP;
  1425. bb.addPoint(pp.current.x, pp.current.y);
  1426. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1427. }
  1428. break;
  1429. case 'C':
  1430. while (!pp.isCommandOrEnd()) {
  1431. var curr = pp.current;
  1432. var p1 = pp.getPoint();
  1433. var cntrl = pp.getAsControlPoint();
  1434. var cp = pp.getAsCurrentPoint();
  1435. pp.addMarker(cp, cntrl, p1);
  1436. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1437. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1438. }
  1439. break;
  1440. case 'S':
  1441. while (!pp.isCommandOrEnd()) {
  1442. var curr = pp.current;
  1443. var p1 = pp.getReflectedControlPoint();
  1444. var cntrl = pp.getAsControlPoint();
  1445. var cp = pp.getAsCurrentPoint();
  1446. pp.addMarker(cp, cntrl, p1);
  1447. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1448. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1449. }
  1450. break;
  1451. case 'Q':
  1452. while (!pp.isCommandOrEnd()) {
  1453. var curr = pp.current;
  1454. var cntrl = pp.getAsControlPoint();
  1455. var cp = pp.getAsCurrentPoint();
  1456. pp.addMarker(cp, cntrl, cntrl);
  1457. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1458. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1459. }
  1460. break;
  1461. case 'T':
  1462. while (!pp.isCommandOrEnd()) {
  1463. var curr = pp.current;
  1464. var cntrl = pp.getReflectedControlPoint();
  1465. pp.control = cntrl;
  1466. var cp = pp.getAsCurrentPoint();
  1467. pp.addMarker(cp, cntrl, cntrl);
  1468. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1469. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1470. }
  1471. break;
  1472. case 'A':
  1473. while (!pp.isCommandOrEnd()) {
  1474. var curr = pp.current;
  1475. var rx = pp.getScalar();
  1476. var ry = pp.getScalar();
  1477. var xAxisRotation = pp.getScalar() * (Math.PI / 180.0);
  1478. var largeArcFlag = pp.getScalar();
  1479. var sweepFlag = pp.getScalar();
  1480. var cp = pp.getAsCurrentPoint();
  1481. // Conversion from endpoint to center parameterization
  1482. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  1483. // x1', y1'
  1484. var currp = new svg.Point(
  1485. Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,
  1486. -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
  1487. );
  1488. // adjust radii
  1489. var l = Math.pow(currp.x, 2) / Math.pow(rx, 2) + Math.pow(currp.y, 2) / Math.pow(ry, 2);
  1490. if (l > 1) {
  1491. rx *= Math.sqrt(l);
  1492. ry *= Math.sqrt(l);
  1493. }
  1494. // cx', cy'
  1495. var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
  1496. ((Math.pow(rx, 2) * Math.pow(ry, 2)) - (Math.pow(rx, 2) * Math.pow(currp.y, 2)) - (Math.pow(ry, 2) * Math.pow(currp.x, 2))) /
  1497. (Math.pow(rx, 2) * Math.pow(currp.y, 2) + Math.pow(ry, 2) * Math.pow(currp.x, 2))
  1498. );
  1499. if (isNaN(s)) s = 0;
  1500. var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
  1501. // cx, cy
  1502. var centp = new svg.Point(
  1503. (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
  1504. (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
  1505. );
  1506. // vector magnitude
  1507. var m = function (v) {
  1508. return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2));
  1509. }
  1510. // ratio between two vectors
  1511. var r = function (u, v) {
  1512. return (u[0] * v[0] + u[1] * v[1]) / (m(u) * m(v))
  1513. }
  1514. // angle between two vectors
  1515. var a = function (u, v) {
  1516. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(r(u, v));
  1517. }
  1518. // initial angle
  1519. var a1 = a([1, 0], [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]);
  1520. // angle delta
  1521. var u = [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry];
  1522. var v = [(-currp.x - cpp.x) / rx, (-currp.y - cpp.y) / ry];
  1523. var ad = a(u, v);
  1524. if (r(u, v) <= -1) ad = Math.PI;
  1525. if (r(u, v) >= 1) ad = 0;
  1526. if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI;
  1527. if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI;
  1528. // for markers
  1529. var halfWay = new svg.Point(
  1530. centp.x - rx * Math.cos((a1 + ad) / 2),
  1531. centp.y - ry * Math.sin((a1 + ad) / 2)
  1532. );
  1533. pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
  1534. pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
  1535. bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better
  1536. if (ctx != null) {
  1537. var r = rx > ry ? rx : ry;
  1538. var sx = rx > ry ? 1 : rx / ry;
  1539. var sy = rx > ry ? ry / rx : 1;
  1540. ctx.translate(centp.x, centp.y);
  1541. ctx.rotate(xAxisRotation);
  1542. ctx.scale(sx, sy);
  1543. ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);
  1544. ctx.scale(1 / sx, 1 / sy);
  1545. ctx.rotate(-xAxisRotation);
  1546. ctx.translate(-centp.x, -centp.y);
  1547. }
  1548. }
  1549. break;
  1550. case 'Z':
  1551. if (ctx != null) ctx.closePath();
  1552. pp.current = pp.start;
  1553. }
  1554. }
  1555. return bb;
  1556. }
  1557. this.getMarkers = function () {
  1558. var points = this.PathParser.getMarkerPoints();
  1559. var angles = this.PathParser.getMarkerAngles();
  1560. var markers = [];
  1561. for (var i = 0; i < points.length; i++) {
  1562. markers.push([points[i], angles[i]]);
  1563. }
  1564. return markers;
  1565. }
  1566. }
  1567. svg.Element.path.prototype = new svg.Element.PathElementBase;
  1568. // pattern element
  1569. svg.Element.pattern = function (node) {
  1570. this.base = svg.Element.ElementBase;
  1571. this.base(node);
  1572. this.createPattern = function (ctx, element) {
  1573. // render me using a temporary svg element
  1574. var tempSvg = new svg.Element.svg();
  1575. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1576. tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value);
  1577. tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value);
  1578. tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);
  1579. tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);
  1580. tempSvg.children = this.children;
  1581. var c = document.createElement('canvas');
  1582. c.width = this.attribute('width').Length.toPixels('x');
  1583. c.height = this.attribute('height').Length.toPixels('y');
  1584. tempSvg.render(c.getContext('2d'));
  1585. return ctx.createPattern(c, 'repeat');
  1586. }
  1587. }
  1588. svg.Element.pattern.prototype = new svg.Element.ElementBase;
  1589. // marker element
  1590. svg.Element.marker = function (node) {
  1591. this.base = svg.Element.ElementBase;
  1592. this.base(node);
  1593. this.baseRender = this.render;
  1594. this.render = function (ctx, point, angle) {
  1595. ctx.translate(point.x, point.y);
  1596. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle);
  1597. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);
  1598. ctx.save();
  1599. // render me using a temporary svg element
  1600. var tempSvg = new svg.Element.svg();
  1601. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1602. tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);
  1603. tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);
  1604. tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);
  1605. tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);
  1606. tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));
  1607. tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));
  1608. tempSvg.children = this.children;
  1609. tempSvg.render(ctx);
  1610. ctx.restore();
  1611. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1 / ctx.lineWidth, 1 / ctx.lineWidth);
  1612. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle);
  1613. ctx.translate(-point.x, -point.y);
  1614. }
  1615. }
  1616. svg.Element.marker.prototype = new svg.Element.ElementBase;
  1617. // definitions element
  1618. svg.Element.defs = function (node) {
  1619. this.base = svg.Element.ElementBase;
  1620. this.base(node);
  1621. this.render = function (ctx) {
  1622. // NOOP
  1623. }
  1624. }
  1625. svg.Element.defs.prototype = new svg.Element.ElementBase;
  1626. // base for gradients
  1627. svg.Element.GradientBase = function (node) {
  1628. this.base = svg.Element.ElementBase;
  1629. this.base(node);
  1630. this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');
  1631. this.stops = [];
  1632. for (var i = 0; i < this.children.length; i++) {
  1633. var child = this.children[i];
  1634. this.stops.push(child);
  1635. }
  1636. this.getGradient = function () {
  1637. // OVERRIDE ME!
  1638. }
  1639. this.createGradient = function (ctx, element) {
  1640. var stopsContainer = this;
  1641. if (this.attribute('xlink:href').hasValue()) {
  1642. stopsContainer = this.attribute('xlink:href').Definition.getDefinition();
  1643. }
  1644. var g = this.getGradient(ctx, element);
  1645. for (var i = 0; i < stopsContainer.stops.length; i++) {
  1646. g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color);
  1647. }
  1648. if (this.attribute('gradientTransform').hasValue()) {
  1649. // render as transformed pattern on temporary canvas
  1650. var rootView = svg.ViewPort.viewPorts[0];
  1651. var rect = new svg.Element.rect();
  1652. rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS / 3.0);
  1653. rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS / 3.0);
  1654. rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS);
  1655. rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS);
  1656. var group = new svg.Element.g();
  1657. group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value);
  1658. group.children = [rect];
  1659. var tempSvg = new svg.Element.svg();
  1660. tempSvg.attributes['x'] = new svg.Property('x', 0);
  1661. tempSvg.attributes['y'] = new svg.Property('y', 0);
  1662. tempSvg.attributes['width'] = new svg.Property('width', rootView.width);
  1663. tempSvg.attributes['height'] = new svg.Property('height', rootView.height);
  1664. tempSvg.children = [group];
  1665. var c = document.createElement('canvas');
  1666. c.width = rootView.width;
  1667. c.height = rootView.height;
  1668. var tempCtx = c.getContext('2d');
  1669. tempCtx.fillStyle = g;
  1670. tempSvg.render(tempCtx);
  1671. return tempCtx.createPattern(c, 'no-repeat');
  1672. }
  1673. return g;
  1674. }
  1675. }
  1676. svg.Element.GradientBase.prototype = new svg.Element.ElementBase;
  1677. // linear gradient element
  1678. svg.Element.linearGradient = function (node) {
  1679. this.base = svg.Element.GradientBase;
  1680. this.base(node);
  1681. this.getGradient = function (ctx, element) {
  1682. var bb = element.getBoundingBox();
  1683. var x1 = (this.gradientUnits == 'objectBoundingBox'
  1684. ? bb.x() + bb.width() * this.attribute('x1').numValue()
  1685. : this.attribute('x1').Length.toPixels('x'));
  1686. var y1 = (this.gradientUnits == 'objectBoundingBox'
  1687. ? bb.y() + bb.height() * this.attribute('y1').numValue()
  1688. : this.attribute('y1').Length.toPixels('y'));
  1689. var x2 = (this.gradientUnits == 'objectBoundingBox'
  1690. ? bb.x() + bb.width() * this.attribute('x2').numValue()
  1691. : this.attribute('x2').Length.toPixels('x'));
  1692. var y2 = (this.gradientUnits == 'objectBoundingBox'
  1693. ? bb.y() + bb.height() * this.attribute('y2').numValue()
  1694. : this.attribute('y2').Length.toPixels('y'));
  1695. return ctx.createLinearGradient(x1, y1, x2, y2);
  1696. }
  1697. }
  1698. svg.Element.linearGradient.prototype = new svg.Element.GradientBase;
  1699. // radial gradient element
  1700. svg.Element.radialGradient = function (node) {
  1701. this.base = svg.Element.GradientBase;
  1702. this.base(node);
  1703. this.getGradient = function (ctx, element) {
  1704. var bb = element.getBoundingBox();
  1705. var cx = (this.gradientUnits == 'objectBoundingBox'
  1706. ? bb.x() + bb.width() * this.attribute('cx').numValue()
  1707. : this.attribute('cx').Length.toPixels('x'));
  1708. var cy = (this.gradientUnits == 'objectBoundingBox'
  1709. ? bb.y() + bb.height() * this.attribute('cy').numValue()
  1710. : this.attribute('cy').Length.toPixels('y'));
  1711. var fx = cx;
  1712. var fy = cy;
  1713. if (this.attribute('fx').hasValue()) {
  1714. fx = (this.gradientUnits == 'objectBoundingBox'
  1715. ? bb.x() + bb.width() * this.attribute('fx').numValue()
  1716. : this.attribute('fx').Length.toPixels('x'));
  1717. }
  1718. if (this.attribute('fy').hasValue()) {
  1719. fy = (this.gradientUnits == 'objectBoundingBox'
  1720. ? bb.y() + bb.height() * this.attribute('fy').numValue()
  1721. : this.attribute('fy').Length.toPixels('y'));
  1722. }
  1723. var r = (this.gradientUnits == 'objectBoundingBox'
  1724. ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue()
  1725. : this.attribute('r').Length.toPixels());
  1726. return ctx.createRadialGradient(fx, fy, 0, cx, cy, r);
  1727. }
  1728. }
  1729. svg.Element.radialGradient.prototype = new svg.Element.GradientBase;
  1730. // gradient stop element
  1731. svg.Element.stop = function (node) {
  1732. this.base = svg.Element.ElementBase;
  1733. this.base(node);
  1734. this.offset = this.attribute('offset').numValue();
  1735. var stopColor = this.style('stop-color');
  1736. if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value);
  1737. this.color = stopColor.value;
  1738. }
  1739. svg.Element.stop.prototype = new svg.Element.ElementBase;
  1740. // animation base element
  1741. svg.Element.AnimateBase = function (node) {
  1742. this.base = svg.Element.ElementBase;
  1743. this.base(node);
  1744. svg.Animations.push(this);
  1745. this.duration = 0.0;
  1746. this.begin = this.attribute('begin').Time.toMilliseconds();
  1747. this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds();
  1748. this.getProperty = function () {
  1749. var attributeType = this.attribute('attributeType').value;
  1750. var attributeName = this.attribute('attributeName').value;
  1751. if (attributeType == 'CSS') {
  1752. return this.parent.style(attributeName, true);
  1753. }
  1754. return this.parent.attribute(attributeName, true);
  1755. };
  1756. this.initialValue = null;
  1757. this.removed = false;
  1758. this.calcValue = function () {
  1759. // OVERRIDE ME!
  1760. return '';
  1761. }
  1762. this.update = function (delta) {
  1763. // set initial value
  1764. if (this.initialValue == null) {
  1765. this.initialValue = this.getProperty().value;
  1766. }
  1767. // if we're past the end time
  1768. if (this.duration > this.maxDuration) {
  1769. // loop for indefinitely repeating animations
  1770. if (this.attribute('repeatCount').value == 'indefinite') {
  1771. this.duration = 0.0
  1772. } else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) {
  1773. this.removed = true;
  1774. this.getProperty().value = this.initialValue;
  1775. return true;
  1776. } else {
  1777. return false; // no updates made
  1778. }
  1779. }
  1780. this.duration = this.duration + delta;
  1781. // if we're past the begin time
  1782. var updated = false;
  1783. if (this.begin < this.duration) {
  1784. var newValue = this.calcValue(); // tween
  1785. if (this.attribute('type').hasValue()) {
  1786. // for transform, etc.
  1787. var type = this.attribute('type').value;
  1788. newValue = type + '(' + newValue + ')';
  1789. }
  1790. this.getProperty().value = newValue;
  1791. updated = true;
  1792. }
  1793. return updated;
  1794. }
  1795. // fraction of duration we've covered
  1796. this.progress = function () {
  1797. return ((this.duration - this.begin) / (this.maxDuration - this.begin));
  1798. }
  1799. }
  1800. svg.Element.AnimateBase.prototype = new svg.Element.ElementBase;
  1801. // animate element
  1802. svg.Element.animate = function (node) {
  1803. this.base = svg.Element.AnimateBase;
  1804. this.base(node);
  1805. this.calcValue = function () {
  1806. var from = this.attribute('from').numValue();
  1807. var to = this.attribute('to').numValue();
  1808. // tween value linearly
  1809. return from + (to - from) * this.progress();
  1810. };
  1811. }
  1812. svg.Element.animate.prototype = new svg.Element.AnimateBase;
  1813. // animate color element
  1814. svg.Element.animateColor = function (node) {
  1815. this.base = svg.Element.AnimateBase;
  1816. this.base(node);
  1817. this.calcValue = function () {
  1818. var from = new RGBColor(this.attribute('from').value);
  1819. var to = new RGBColor(this.attribute('to').value);
  1820. if (from.ok && to.ok) {
  1821. // tween color linearly
  1822. var r = from.r + (to.r - from.r) * this.progress();
  1823. var g = from.g + (to.g - from.g) * this.progress();
  1824. var b = from.b + (to.b - from.b) * this.progress();
  1825. return 'rgb(' + parseInt(r, 10) + ',' + parseInt(g, 10) + ',' + parseInt(b, 10) + ')';
  1826. }
  1827. return this.attribute('from').value;
  1828. };
  1829. }
  1830. svg.Element.animateColor.prototype = new svg.Element.AnimateBase;
  1831. // animate transform element
  1832. svg.Element.animateTransform = function (node) {
  1833. this.base = svg.Element.animate;
  1834. this.base(node);
  1835. }
  1836. svg.Element.animateTransform.prototype = new svg.Element.animate;
  1837. // font element
  1838. svg.Element.font = function (node) {
  1839. this.base = svg.Element.ElementBase;
  1840. this.base(node);
  1841. this.horizAdvX = this.attribute('horiz-adv-x').numValue();
  1842. this.isRTL = false;
  1843. this.isArabic = false;
  1844. this.fontFace = null;
  1845. this.missingGlyph = null;
  1846. this.glyphs = [];
  1847. for (var i = 0; i < this.children.length; i++) {
  1848. var child = this.children[i];
  1849. if (child.type == 'font-face') {
  1850. this.fontFace = child;
  1851. if (child.style('font-family').hasValue()) {
  1852. svg.Definitions[child.style('font-family').value] = this;
  1853. }
  1854. } else if (child.type == 'missing-glyph') this.missingGlyph = child;
  1855. else if (child.type == 'glyph') {
  1856. if (child.arabicForm != '') {
  1857. this.isRTL = true;
  1858. this.isArabic = true;
  1859. if (typeof (this.glyphs[child.unicode]) == 'undefined') this.glyphs[child.unicode] = [];
  1860. this.glyphs[child.unicode][child.arabicForm] = child;
  1861. } else {
  1862. this.glyphs[child.unicode] = child;
  1863. }
  1864. }
  1865. }
  1866. }
  1867. svg.Element.font.prototype = new svg.Element.ElementBase;
  1868. // font-face element
  1869. svg.Element.fontface = function (node) {
  1870. this.base = svg.Element.ElementBase;
  1871. this.base(node);
  1872. this.ascent = this.attribute('ascent').value;
  1873. this.descent = this.attribute('descent').value;
  1874. this.unitsPerEm = this.attribute('units-per-em').numValue();
  1875. }
  1876. svg.Element.fontface.prototype = new svg.Element.ElementBase;
  1877. // missing-glyph element
  1878. svg.Element.missingglyph = function (node) {
  1879. this.base = svg.Element.path;
  1880. this.base(node);
  1881. this.horizAdvX = 0;
  1882. }
  1883. svg.Element.missingglyph.prototype = new svg.Element.path;
  1884. // glyph element
  1885. svg.Element.glyph = function (node) {
  1886. this.base = svg.Element.path;
  1887. this.base(node);
  1888. this.horizAdvX = this.attribute('horiz-adv-x').numValue();
  1889. this.unicode = this.attribute('unicode').value;
  1890. this.arabicForm = this.attribute('arabic-form').value;
  1891. }
  1892. svg.Element.glyph.prototype = new svg.Element.path;
  1893. // text element
  1894. svg.Element.text = function (node) {
  1895. this.base = svg.Element.RenderedElementBase;
  1896. this.base(node);
  1897. if (node != null) {
  1898. // add children
  1899. this.children = [];
  1900. for (var i = 0; i < node.childNodes.length; i++) {
  1901. var childNode = node.childNodes[i];
  1902. if (childNode.nodeType == 1) { // capture tspan and tref nodes
  1903. this.addChild(childNode, true);
  1904. } else if (childNode.nodeType == 3) { // capture text
  1905. this.addChild(new svg.Element.tspan(childNode), false);
  1906. }
  1907. }
  1908. }
  1909. this.baseSetContext = this.setContext;
  1910. this.setContext = function (ctx) {
  1911. this.baseSetContext(ctx);
  1912. if (this.style('dominant-baseline').hasValue()) ctx.textBaseline = this.style('dominant-baseline').value;
  1913. if (this.style('alignment-baseline').hasValue()) ctx.textBaseline = this.style('alignment-baseline').value;
  1914. }
  1915. this.renderChildren = function (ctx) {
  1916. var textAnchor = this.style('text-anchor').valueOrDefault('start');
  1917. var x = this.attribute('x').Length.toPixels('x');
  1918. var y = this.attribute('y').Length.toPixels('y');
  1919. for (var i = 0; i < this.children.length; i++) {
  1920. var child = this.children[i];
  1921. if (child.attribute('x').hasValue()) {
  1922. child.x = child.attribute('x').Length.toPixels('x');
  1923. } else {
  1924. if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x');
  1925. child.x = x;
  1926. }
  1927. var childLength = child.measureText(ctx);
  1928. if (textAnchor != 'start' && (i == 0 || child.attribute('x').hasValue())) { // new group?
  1929. // loop through rest of children
  1930. var groupLength = childLength;
  1931. for (var j = i + 1; j < this.children.length; j++) {
  1932. var childInGroup = this.children[j];
  1933. if (childInGroup.attribute('x').hasValue()) break; // new group
  1934. groupLength += childInGroup.measureText(ctx);
  1935. }
  1936. child.x -= (textAnchor == 'end' ? groupLength : groupLength / 2.0);
  1937. }
  1938. x = child.x + childLength;
  1939. if (child.attribute('y').hasValue()) {
  1940. child.y = child.attribute('y').Length.toPixels('y');
  1941. } else {
  1942. if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y');
  1943. child.y = y;
  1944. }
  1945. y = child.y;
  1946. child.render(ctx);
  1947. }
  1948. }
  1949. }
  1950. svg.Element.text.prototype = new svg.Element.RenderedElementBase;
  1951. // text base
  1952. svg.Element.TextElementBase = function (node) {
  1953. this.base = svg.Element.RenderedElementBase;
  1954. this.base(node);
  1955. this.getGlyph = function (font, text, i) {
  1956. var c = text[i];
  1957. var glyph = null;
  1958. if (font.isArabic) {
  1959. var arabicForm = 'isolated';
  1960. if ((i == 0 || text[i - 1] == ' ') && i < text.length - 2 && text[i + 1] != ' ') arabicForm = 'terminal';
  1961. if (i > 0 && text[i - 1] != ' ' && i < text.length - 2 && text[i + 1] != ' ') arabicForm = 'medial';
  1962. if (i > 0 && text[i - 1] != ' ' && (i == text.length - 1 || text[i + 1] == ' ')) arabicForm = 'initial';
  1963. if (typeof (font.glyphs[c]) != 'undefined') {
  1964. glyph = font.glyphs[c][arabicForm];
  1965. if (glyph == null && font.glyphs[c].type == 'glyph') glyph = font.glyphs[c];
  1966. }
  1967. } else {
  1968. glyph = font.glyphs[c];
  1969. }
  1970. if (glyph == null) glyph = font.missingGlyph;
  1971. return glyph;
  1972. }
  1973. this.renderChildren = function (ctx) {
  1974. var customFont = this.parent.style('font-family').Definition.getDefinition();
  1975. if (customFont != null) {
  1976. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  1977. var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle);
  1978. var text = this.getText();
  1979. if (customFont.isRTL) text = text.split("").reverse().join("");
  1980. var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
  1981. for (var i = 0; i < text.length; i++) {
  1982. var glyph = this.getGlyph(customFont, text, i);
  1983. var scale = fontSize / customFont.fontFace.unitsPerEm;
  1984. ctx.translate(this.x, this.y);
  1985. ctx.scale(scale, -scale);
  1986. var lw = ctx.lineWidth;
  1987. ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize;
  1988. if (fontStyle == 'italic') ctx.transform(1, 0, .4, 1, 0, 0);
  1989. glyph.render(ctx);
  1990. if (fontStyle == 'italic') ctx.transform(1, 0, -.4, 1, 0, 0);
  1991. ctx.lineWidth = lw;
  1992. ctx.scale(1 / scale, -1 / scale);
  1993. ctx.translate(-this.x, -this.y);
  1994. this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm;
  1995. if (typeof (dx[i]) != 'undefined' && !isNaN(dx[i])) {
  1996. this.x += dx[i];
  1997. }
  1998. }
  1999. return;
  2000. }
  2001. if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y);
  2002. if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
  2003. }
  2004. this.getText = function () {
  2005. // OVERRIDE ME
  2006. }
  2007. this.measureText = function (ctx) {
  2008. var customFont = this.parent.style('font-family').Definition.getDefinition();
  2009. if (customFont != null) {
  2010. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  2011. var measure = 0;
  2012. var text = this.getText();
  2013. if (customFont.isRTL) text = text.split("").reverse().join("");
  2014. var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
  2015. for (var i = 0; i < text.length; i++) {
  2016. var glyph = this.getGlyph(customFont, text, i);
  2017. measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm;
  2018. if (typeof (dx[i]) != 'undefined' && !isNaN(dx[i])) {
  2019. measure += dx[i];
  2020. }
  2021. }
  2022. return measure;
  2023. }
  2024. var textToMeasure = svg.compressSpaces(this.getText());
  2025. if (!ctx.measureText) return textToMeasure.length * 10;
  2026. ctx.save();
  2027. this.setContext(ctx);
  2028. var width = ctx.measureText(textToMeasure).width;
  2029. ctx.restore();
  2030. return width;
  2031. }
  2032. }
  2033. svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase;
  2034. // tspan
  2035. svg.Element.tspan = function (node) {
  2036. this.base = svg.Element.TextElementBase;
  2037. this.base(node);
  2038. this.text = node.nodeType == 3 ? node.nodeValue : // text
  2039. node.childNodes.length > 0 ? node.childNodes[0].nodeValue : // element
  2040. node.text;
  2041. this.getText = function () {
  2042. return this.text;
  2043. }
  2044. }
  2045. svg.Element.tspan.prototype = new svg.Element.TextElementBase;
  2046. // tref
  2047. svg.Element.tref = function (node) {
  2048. this.base = svg.Element.TextElementBase;
  2049. this.base(node);
  2050. this.getText = function () {
  2051. var element = this.attribute('xlink:href').Definition.getDefinition();
  2052. if (element != null) return element.children[0].getText();
  2053. }
  2054. }
  2055. svg.Element.tref.prototype = new svg.Element.TextElementBase;
  2056. // a element
  2057. svg.Element.a = function (node) {
  2058. this.base = svg.Element.TextElementBase;
  2059. this.base(node);
  2060. this.hasText = true;
  2061. for (var i = 0; i < node.childNodes.length; i++) {
  2062. if (node.childNodes[i].nodeType != 3) this.hasText = false;
  2063. }
  2064. // this might contain text
  2065. this.text = this.hasText ? node.childNodes[0].nodeValue : '';
  2066. this.getText = function () {
  2067. return this.text;
  2068. }
  2069. this.baseRenderChildren = this.renderChildren;
  2070. this.renderChildren = function (ctx) {
  2071. if (this.hasText) {
  2072. // render as text element
  2073. this.baseRenderChildren(ctx);
  2074. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  2075. svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y));
  2076. } else {
  2077. // render as temporary group
  2078. var g = new svg.Element.g();
  2079. g.children = this.children;
  2080. g.parent = this;
  2081. g.render(ctx);
  2082. }
  2083. }
  2084. this.onclick = function () {
  2085. window.open(this.attribute('xlink:href').value);
  2086. }
  2087. this.onmousemove = function () {
  2088. svg.ctx.canvas.style.cursor = 'pointer';
  2089. }
  2090. }
  2091. svg.Element.a.prototype = new svg.Element.TextElementBase;
  2092. // image element
  2093. svg.Element.image = function (node) {
  2094. this.base = svg.Element.RenderedElementBase;
  2095. this.base(node);
  2096. svg.Images.push(this);
  2097. this.img = document.createElement('img');
  2098. this.loaded = false;
  2099. var that = this;
  2100. this.img.onload = function () {
  2101. that.loaded = true;
  2102. }
  2103. this.img.src = this.attribute('xlink:href').value;
  2104. this.renderChildren = function (ctx) {
  2105. var x = this.attribute('x').Length.toPixels('x');
  2106. var y = this.attribute('y').Length.toPixels('y');
  2107. var width = this.attribute('width').Length.toPixels('x');
  2108. var height = this.attribute('height').Length.toPixels('y');
  2109. if (width == 0 || height == 0) return;
  2110. ctx.save();
  2111. ctx.translate(x, y);
  2112. svg.AspectRatio(ctx,
  2113. this.attribute('preserveAspectRatio').value,
  2114. width,
  2115. this.img.width,
  2116. height,
  2117. this.img.height,
  2118. 0,
  2119. 0);
  2120. ctx.drawImage(this.img, 0, 0);
  2121. ctx.restore();
  2122. }
  2123. }
  2124. svg.Element.image.prototype = new svg.Element.RenderedElementBase;
  2125. // group element
  2126. svg.Element.g = function (node) {
  2127. this.base = svg.Element.RenderedElementBase;
  2128. this.base(node);
  2129. this.getBoundingBox = function () {
  2130. var bb = new svg.BoundingBox();
  2131. for (var i = 0; i < this.children.length; i++) {
  2132. bb.addBoundingBox(this.children[i].getBoundingBox());
  2133. }
  2134. return bb;
  2135. };
  2136. }
  2137. svg.Element.g.prototype = new svg.Element.RenderedElementBase;
  2138. // symbol element
  2139. svg.Element.symbol = function (node) {
  2140. this.base = svg.Element.RenderedElementBase;
  2141. this.base(node);
  2142. this.baseSetContext = this.setContext;
  2143. this.setContext = function (ctx) {
  2144. this.baseSetContext(ctx);
  2145. // viewbox
  2146. if (this.attribute('viewBox').hasValue()) {
  2147. var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
  2148. var minX = viewBox[0];
  2149. var minY = viewBox[1];
  2150. width = viewBox[2];
  2151. height = viewBox[3];
  2152. svg.AspectRatio(ctx,
  2153. this.attribute('preserveAspectRatio').value,
  2154. this.attribute('width').Length.toPixels('x'),
  2155. width,
  2156. this.attribute('height').Length.toPixels('y'),
  2157. height,
  2158. minX,
  2159. minY);
  2160. svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
  2161. }
  2162. }
  2163. }
  2164. svg.Element.symbol.prototype = new svg.Element.RenderedElementBase;
  2165. // style element
  2166. svg.Element.style = function (node) {
  2167. this.base = svg.Element.ElementBase;
  2168. this.base(node);
  2169. // text, or spaces then CDATA
  2170. var css = node.childNodes[0].nodeValue + (node.childNodes.length > 1 ? node.childNodes[1].nodeValue : '');
  2171. css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(^[\s]*\/\/.*)/gm, ''); // remove comments
  2172. css = svg.compressSpaces(css); // replace whitespace
  2173. var cssDefs = css.split('}');
  2174. for (var i = 0; i < cssDefs.length; i++) {
  2175. if (svg.trim(cssDefs[i]) != '') {
  2176. var cssDef = cssDefs[i].split('{');
  2177. var cssClasses = cssDef[0].split(',');
  2178. var cssProps = cssDef[1].split(';');
  2179. for (var j = 0; j < cssClasses.length; j++) {
  2180. var cssClass = svg.trim(cssClasses[j]);
  2181. if (cssClass != '') {
  2182. var props = {};
  2183. for (var k = 0; k < cssProps.length; k++) {
  2184. var prop = cssProps[k].indexOf(':');
  2185. var name = cssProps[k].substr(0, prop);
  2186. var value = cssProps[k].substr(prop + 1, cssProps[k].length - prop);
  2187. if (name != null && value != null) {
  2188. props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value));
  2189. }
  2190. }
  2191. svg.Styles[cssClass] = props;
  2192. if (cssClass == '@font-face') {
  2193. var fontFamily = props['font-family'].value.replace(/"/g, '');
  2194. var srcs = props['src'].value.split(',');
  2195. for (var s = 0; s < srcs.length; s++) {
  2196. if (srcs[s].indexOf('format("svg")') > 0) {
  2197. var urlStart = srcs[s].indexOf('url');
  2198. var urlEnd = srcs[s].indexOf(')', urlStart);
  2199. var url = srcs[s].substr(urlStart + 5, urlEnd - urlStart - 6);
  2200. var doc = svg.parseXml(svg.ajax(url));
  2201. var fonts = doc.getElementsByTagName('font');
  2202. for (var f = 0; f < fonts.length; f++) {
  2203. var font = svg.CreateElement(fonts[f]);
  2204. svg.Definitions[fontFamily] = font;
  2205. }
  2206. }
  2207. }
  2208. }
  2209. }
  2210. }
  2211. }
  2212. }
  2213. }
  2214. svg.Element.style.prototype = new svg.Element.ElementBase;
  2215. // use element
  2216. svg.Element.use = function (node) {
  2217. this.base = svg.Element.RenderedElementBase;
  2218. this.base(node);
  2219. this.baseSetContext = this.setContext;
  2220. this.setContext = function (ctx) {
  2221. this.baseSetContext(ctx);
  2222. if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0);
  2223. if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y'));
  2224. }
  2225. this.getDefinition = function () {
  2226. var element = this.attribute('xlink:href').Definition.getDefinition();
  2227. if (this.attribute('width').hasValue()) element.attribute('width', true).value = this.attribute('width').value;
  2228. if (this.attribute('height').hasValue()) element.attribute('height', true).value = this.attribute('height').value;
  2229. return element;
  2230. }
  2231. this.path = function (ctx) {
  2232. var element = this.getDefinition();
  2233. if (element != null) element.path(ctx);
  2234. }
  2235. this.renderChildren = function (ctx) {
  2236. var element = this.getDefinition();
  2237. if (element != null) element.render(ctx);
  2238. }
  2239. }
  2240. svg.Element.use.prototype = new svg.Element.RenderedElementBase;
  2241. // mask element
  2242. svg.Element.mask = function (node) {
  2243. this.base = svg.Element.ElementBase;
  2244. this.base(node);
  2245. this.apply = function (ctx, element) {
  2246. // render as temp svg
  2247. var x = this.attribute('x').Length.toPixels('x');
  2248. var y = this.attribute('y').Length.toPixels('y');
  2249. var width = this.attribute('width').Length.toPixels('x');
  2250. var height = this.attribute('height').Length.toPixels('y');
  2251. // temporarily remove mask to avoid recursion
  2252. var mask = element.attribute('mask').value;
  2253. element.attribute('mask').value = '';
  2254. var cMask = document.createElement('canvas');
  2255. cMask.width = x + width;
  2256. cMask.height = y + height;
  2257. var maskCtx = cMask.getContext('2d');
  2258. this.renderChildren(maskCtx);
  2259. var c = document.createElement('canvas');
  2260. c.width = x + width;
  2261. c.height = y + height;
  2262. var tempCtx = c.getContext('2d');
  2263. element.render(tempCtx);
  2264. tempCtx.globalCompositeOperation = 'destination-in';
  2265. tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat');
  2266. tempCtx.fillRect(0, 0, x + width, y + height);
  2267. ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat');
  2268. ctx.fillRect(0, 0, x + width, y + height);
  2269. // reassign mask
  2270. element.attribute('mask').value = mask;
  2271. }
  2272. this.render = function (ctx) {
  2273. // NO RENDER
  2274. }
  2275. }
  2276. svg.Element.mask.prototype = new svg.Element.ElementBase;
  2277. // clip element
  2278. svg.Element.clipPath = function (node) {
  2279. this.base = svg.Element.ElementBase;
  2280. this.base(node);
  2281. this.apply = function (ctx) {
  2282. for (var i = 0; i < this.children.length; i++) {
  2283. if (this.children[i].path) {
  2284. this.children[i].path(ctx);
  2285. ctx.clip();
  2286. }
  2287. }
  2288. }
  2289. this.render = function (ctx) {
  2290. // NO RENDER
  2291. }
  2292. }
  2293. svg.Element.clipPath.prototype = new svg.Element.ElementBase;
  2294. // filters
  2295. svg.Element.filter = function (node) {
  2296. this.base = svg.Element.ElementBase;
  2297. this.base(node);
  2298. this.apply = function (ctx, element) {
  2299. // render as temp svg
  2300. var bb = element.getBoundingBox();
  2301. var x = this.attribute('x').Length.toPixels('x');
  2302. var y = this.attribute('y').Length.toPixels('y');
  2303. if (x == 0 || y == 0) {
  2304. x = bb.x1;
  2305. y = bb.y1;
  2306. }
  2307. var width = this.attribute('width').Length.toPixels('x');
  2308. var height = this.attribute('height').Length.toPixels('y');
  2309. if (width == 0 || height == 0) {
  2310. width = bb.width();
  2311. height = bb.height();
  2312. }
  2313. // temporarily remove filter to avoid recursion
  2314. var filter = element.style('filter').value;
  2315. element.style('filter').value = '';
  2316. // max filter distance
  2317. var extraPercent = .20;
  2318. var px = extraPercent * width;
  2319. var py = extraPercent * height;
  2320. var c = document.createElement('canvas');
  2321. c.width = width + 2 * px;
  2322. c.height = height + 2 * py;
  2323. var tempCtx = c.getContext('2d');
  2324. tempCtx.translate(-x + px, -y + py);
  2325. element.render(tempCtx);
  2326. // apply filters
  2327. for (var i = 0; i < this.children.length; i++) {
  2328. this.children[i].apply(tempCtx, 0, 0, width + 2 * px, height + 2 * py);
  2329. }
  2330. // render on me
  2331. ctx.drawImage(c, 0, 0, width + 2 * px, height + 2 * py, x - px, y - py, width + 2 * px, height + 2 * py);
  2332. // reassign filter
  2333. element.style('filter', true).value = filter;
  2334. }
  2335. this.render = function (ctx) {
  2336. // NO RENDER
  2337. }
  2338. }
  2339. svg.Element.filter.prototype = new svg.Element.ElementBase;
  2340. svg.Element.feGaussianBlur = function (node) {
  2341. this.base = svg.Element.ElementBase;
  2342. this.base(node);
  2343. function make_fgauss(sigma) {
  2344. sigma = Math.max(sigma, 0.01);
  2345. var len = Math.ceil(sigma * 4.0) + 1;
  2346. mask = [];
  2347. for (var i = 0; i < len; i++) {
  2348. mask[i] = Math.exp(-0.5 * (i / sigma) * (i / sigma));
  2349. }
  2350. return mask;
  2351. }
  2352. function normalize(mask) {
  2353. var sum = 0;
  2354. for (var i = 1; i < mask.length; i++) {
  2355. sum += Math.abs(mask[i]);
  2356. }
  2357. sum = 2 * sum + Math.abs(mask[0]);
  2358. for (var i = 0; i < mask.length; i++) {
  2359. mask[i] /= sum;
  2360. }
  2361. return mask;
  2362. }
  2363. function convolve_even(src, dst, mask, width, height) {
  2364. for (var y = 0; y < height; y++) {
  2365. for (var x = 0; x < width; x++) {
  2366. var a = imGet(src, x, y, width, height, 3) / 255;
  2367. for (var rgba = 0; rgba < 4; rgba++) {
  2368. var sum = mask[0] * (a == 0 ? 255 : imGet(src, x, y, width, height, rgba)) * (a == 0 || rgba == 3 ? 1 : a);
  2369. for (var i = 1; i < mask.length; i++) {
  2370. var a1 = imGet(src, Math.max(x - i, 0), y, width, height, 3) / 255;
  2371. var a2 = imGet(src, Math.min(x + i, width - 1), y, width, height, 3) / 255;
  2372. sum += mask[i] *
  2373. ((a1 == 0 ? 255 : imGet(src, Math.max(x - i, 0), y, width, height, rgba)) * (a1 == 0 || rgba == 3 ? 1 : a1) +
  2374. (a2 == 0 ? 255 : imGet(src, Math.min(x + i, width - 1), y, width, height, rgba)) * (a2 == 0 || rgba == 3 ? 1 : a2));
  2375. }
  2376. imSet(dst, y, x, height, width, rgba, sum);
  2377. }
  2378. }
  2379. }
  2380. }
  2381. function imGet(img, x, y, width, height, rgba) {
  2382. return img[y * width * 4 + x * 4 + rgba];
  2383. }
  2384. function imSet(img, x, y, width, height, rgba, val) {
  2385. img[y * width * 4 + x * 4 + rgba] = val;
  2386. }
  2387. function blur(ctx, width, height, sigma) {
  2388. var srcData = ctx.getImageData(0, 0, width, height);
  2389. var mask = make_fgauss(sigma);
  2390. mask = normalize(mask);
  2391. tmp = [];
  2392. convolve_even(srcData.data, tmp, mask, width, height);
  2393. convolve_even(tmp, srcData.data, mask, height, width);
  2394. ctx.clearRect(0, 0, width, height);
  2395. ctx.putImageData(srcData, 0, 0);
  2396. }
  2397. this.apply = function (ctx, x, y, width, height) {
  2398. // assuming x==0 && y==0 for now
  2399. blur(ctx, width, height, this.attribute('stdDeviation').numValue());
  2400. }
  2401. }
  2402. svg.Element.filter.prototype = new svg.Element.feGaussianBlur;
  2403. // title element, do nothing
  2404. svg.Element.title = function (node) {
  2405. }
  2406. svg.Element.title.prototype = new svg.Element.ElementBase;
  2407. // desc element, do nothing
  2408. svg.Element.desc = function (node) {
  2409. }
  2410. svg.Element.desc.prototype = new svg.Element.ElementBase;
  2411. svg.Element.MISSING = function (node) {
  2412. console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.');
  2413. }
  2414. svg.Element.MISSING.prototype = new svg.Element.ElementBase;
  2415. // element factory
  2416. svg.CreateElement = function (node) {
  2417. var className = node.nodeName.replace(/^[^:]+:/, ''); // remove namespace
  2418. className = className.replace(/\-/g, ''); // remove dashes
  2419. var e = null;
  2420. if (typeof (svg.Element[className]) != 'undefined') {
  2421. e = new svg.Element[className](node);
  2422. } else {
  2423. e = new svg.Element.MISSING(node);
  2424. }
  2425. e.type = node.nodeName;
  2426. return e;
  2427. }
  2428. // load from url
  2429. svg.load = function (ctx, url) {
  2430. svg.loadXml(ctx, svg.ajax(url));
  2431. }
  2432. // load from xml
  2433. svg.loadXml = function (ctx, xml) {
  2434. svg.loadXmlDoc(ctx, svg.parseXml(xml));
  2435. }
  2436. svg.loadXmlDoc = function (ctx, dom) {
  2437. svg.init(ctx);
  2438. var mapXY = function (p) {
  2439. var e = ctx.canvas;
  2440. while (e) {
  2441. p.x -= e.offsetLeft;
  2442. p.y -= e.offsetTop;
  2443. e = e.offsetParent;
  2444. }
  2445. if (window.scrollX) p.x += window.scrollX;
  2446. if (window.scrollY) p.y += window.scrollY;
  2447. return p;
  2448. }
  2449. // bind mouse
  2450. if (svg.opts['ignoreMouse'] != true) {
  2451. ctx.canvas.onclick = function (e) {
  2452. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  2453. svg.Mouse.onclick(p.x, p.y);
  2454. };
  2455. ctx.canvas.onmousemove = function (e) {
  2456. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  2457. svg.Mouse.onmousemove(p.x, p.y);
  2458. };
  2459. }
  2460. var e = svg.CreateElement(dom.documentElement);
  2461. e.root = true;
  2462. // render loop
  2463. var isFirstRender = true;
  2464. var draw = function () {
  2465. svg.ViewPort.Clear();
  2466. if (ctx.canvas.parentNode) svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight);
  2467. if (svg.opts['ignoreDimensions'] != true) {
  2468. // set canvas size
  2469. if (e.style('width').hasValue()) {
  2470. ctx.canvas.width = e.style('width').Length.toPixels('x');
  2471. ctx.canvas.style.width = ctx.canvas.width + 'px';
  2472. }
  2473. if (e.style('height').hasValue()) {
  2474. ctx.canvas.height = e.style('height').Length.toPixels('y');
  2475. ctx.canvas.style.height = ctx.canvas.height + 'px';
  2476. }
  2477. }
  2478. var cWidth = ctx.canvas.clientWidth || ctx.canvas.width;
  2479. var cHeight = ctx.canvas.clientHeight || ctx.canvas.height;
  2480. svg.ViewPort.SetCurrent(cWidth, cHeight);
  2481. if (svg.opts != null && svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX'];
  2482. if (svg.opts != null && svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY'];
  2483. if (svg.opts != null && svg.opts['scaleWidth'] != null && svg.opts['scaleHeight'] != null) {
  2484. var xRatio = 1, yRatio = 1;
  2485. if (e.attribute('width').hasValue()) xRatio = e.attribute('width').Length.toPixels('x') / svg.opts['scaleWidth'];
  2486. if (e.attribute('height').hasValue()) yRatio = e.attribute('height').Length.toPixels('y') / svg.opts['scaleHeight'];
  2487. e.attribute('width', true).value = svg.opts['scaleWidth'];
  2488. e.attribute('height', true).value = svg.opts['scaleHeight'];
  2489. e.attribute('viewBox', true).value = '0 0 ' + (cWidth * xRatio) + ' ' + (cHeight * yRatio);
  2490. e.attribute('preserveAspectRatio', true).value = 'none';
  2491. }
  2492. // clear and render
  2493. if (svg.opts['ignoreClear'] != true) {
  2494. ctx.clearRect(0, 0, cWidth, cHeight);
  2495. }
  2496. e.render(ctx);
  2497. if (isFirstRender) {
  2498. isFirstRender = false;
  2499. if (svg.opts != null && typeof (svg.opts['renderCallback']) == 'function') svg.opts['renderCallback']();
  2500. }
  2501. }
  2502. var waitingForImages = true;
  2503. if (svg.ImagesLoaded()) {
  2504. waitingForImages = false;
  2505. draw();
  2506. }
  2507. svg.intervalID = setInterval(function () {
  2508. var needUpdate = false;
  2509. if (waitingForImages && svg.ImagesLoaded()) {
  2510. waitingForImages = false;
  2511. needUpdate = true;
  2512. }
  2513. // need update from mouse events?
  2514. if (svg.opts['ignoreMouse'] != true) {
  2515. needUpdate = needUpdate | svg.Mouse.hasEvents();
  2516. }
  2517. // need update from animations?
  2518. if (svg.opts['ignoreAnimation'] != true) {
  2519. for (var i = 0; i < svg.Animations.length; i++) {
  2520. needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE);
  2521. }
  2522. }
  2523. // need update from redraw?
  2524. if (svg.opts != null && typeof (svg.opts['forceRedraw']) == 'function') {
  2525. if (svg.opts['forceRedraw']() == true) needUpdate = true;
  2526. }
  2527. // render if needed
  2528. if (needUpdate) {
  2529. draw();
  2530. svg.Mouse.runEvents(); // run and clear our events
  2531. }
  2532. }, 1000 / svg.FRAMERATE);
  2533. }
  2534. svg.stop = function () {
  2535. if (svg.intervalID) {
  2536. clearInterval(svg.intervalID);
  2537. }
  2538. }
  2539. svg.Mouse = new (function () {
  2540. this.events = [];
  2541. this.hasEvents = function () {
  2542. return this.events.length != 0;
  2543. }
  2544. this.onclick = function (x, y) {
  2545. this.events.push({
  2546. type: 'onclick', x: x, y: y,
  2547. run: function (e) {
  2548. if (e.onclick) e.onclick();
  2549. }
  2550. });
  2551. }
  2552. this.onmousemove = function (x, y) {
  2553. this.events.push({
  2554. type: 'onmousemove', x: x, y: y,
  2555. run: function (e) {
  2556. if (e.onmousemove) e.onmousemove();
  2557. }
  2558. });
  2559. }
  2560. this.eventElements = [];
  2561. this.checkPath = function (element, ctx) {
  2562. for (var i = 0; i < this.events.length; i++) {
  2563. var e = this.events[i];
  2564. if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;
  2565. }
  2566. }
  2567. this.checkBoundingBox = function (element, bb) {
  2568. for (var i = 0; i < this.events.length; i++) {
  2569. var e = this.events[i];
  2570. if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;
  2571. }
  2572. }
  2573. this.runEvents = function () {
  2574. svg.ctx.canvas.style.cursor = '';
  2575. for (var i = 0; i < this.events.length; i++) {
  2576. var e = this.events[i];
  2577. var element = this.eventElements[i];
  2578. while (element) {
  2579. e.run(element);
  2580. element = element.parent;
  2581. }
  2582. }
  2583. // done running, clear
  2584. this.events = [];
  2585. this.eventElements = [];
  2586. }
  2587. });
  2588. return svg;
  2589. }
  2590. })();
  2591. if (CanvasRenderingContext2D) {
  2592. CanvasRenderingContext2D.prototype.drawSvg = function (s, dx, dy, dw, dh) {
  2593. canvg(this.canvas, s, {
  2594. ignoreMouse: true,
  2595. ignoreAnimation: true,
  2596. ignoreDimensions: true,
  2597. ignoreClear: true,
  2598. offsetX: dx,
  2599. offsetY: dy,
  2600. scaleWidth: dw,
  2601. scaleHeight: dh
  2602. });
  2603. }
  2604. }/**
  2605. * @license Highcharts JS v3.0.6 (2013-10-04)
  2606. * CanVGRenderer Extension module
  2607. *
  2608. * (c) 2011-2012 Torstein Hønsi, Erik Olsson
  2609. *
  2610. * License: www.highcharts.com/license
  2611. */
  2612. // JSLint options:
  2613. /*global Highcharts */
  2614. (function (Highcharts) { // encapsulate
  2615. var UNDEFINED,
  2616. DIV = 'div',
  2617. ABSOLUTE = 'absolute',
  2618. RELATIVE = 'relative',
  2619. HIDDEN = 'hidden',
  2620. VISIBLE = 'visible',
  2621. PX = 'px',
  2622. css = Highcharts.css,
  2623. CanVGRenderer = Highcharts.CanVGRenderer,
  2624. SVGRenderer = Highcharts.SVGRenderer,
  2625. extend = Highcharts.extend,
  2626. merge = Highcharts.merge,
  2627. addEvent = Highcharts.addEvent,
  2628. createElement = Highcharts.createElement,
  2629. discardElement = Highcharts.discardElement;
  2630. // Extend CanVG renderer on demand, inherit from SVGRenderer
  2631. extend(CanVGRenderer.prototype, SVGRenderer.prototype);
  2632. // Add additional functionality:
  2633. extend(CanVGRenderer.prototype, {
  2634. create: function (chart, container, chartWidth, chartHeight) {
  2635. this.setContainer(container, chartWidth, chartHeight);
  2636. this.configure(chart);
  2637. },
  2638. setContainer: function (container, chartWidth, chartHeight) {
  2639. var containerStyle = container.style,
  2640. containerParent = container.parentNode,
  2641. containerLeft = containerStyle.left,
  2642. containerTop = containerStyle.top,
  2643. containerOffsetWidth = container.offsetWidth,
  2644. containerOffsetHeight = container.offsetHeight,
  2645. canvas,
  2646. initialHiddenStyle = {visibility: HIDDEN, position: ABSOLUTE};
  2647. this.init.apply(this, [container, chartWidth, chartHeight]);
  2648. // add the canvas above it
  2649. canvas = createElement('canvas', {
  2650. width: containerOffsetWidth,
  2651. height: containerOffsetHeight
  2652. }, {
  2653. position: RELATIVE,
  2654. left: containerLeft,
  2655. top: containerTop
  2656. }, container);
  2657. this.canvas = canvas;
  2658. // Create the tooltip line and div, they are placed as siblings to
  2659. // the container (and as direct childs to the div specified in the html page)
  2660. this.ttLine = createElement(DIV, null, initialHiddenStyle, containerParent);
  2661. this.ttDiv = createElement(DIV, null, initialHiddenStyle, containerParent);
  2662. this.ttTimer = UNDEFINED;
  2663. // Move away the svg node to a new div inside the container's parent so we can hide it.
  2664. var hiddenSvg = createElement(DIV, {
  2665. width: containerOffsetWidth,
  2666. height: containerOffsetHeight
  2667. }, {
  2668. visibility: HIDDEN,
  2669. left: containerLeft,
  2670. top: containerTop
  2671. }, containerParent);
  2672. this.hiddenSvg = hiddenSvg;
  2673. hiddenSvg.appendChild(this.box);
  2674. },
  2675. /**
  2676. * Configures the renderer with the chart. Attach a listener to the event tooltipRefresh.
  2677. **/
  2678. configure: function (chart) {
  2679. var renderer = this,
  2680. options = chart.options.tooltip,
  2681. borderWidth = options.borderWidth,
  2682. tooltipDiv = renderer.ttDiv,
  2683. tooltipDivStyle = options.style,
  2684. tooltipLine = renderer.ttLine,
  2685. padding = parseInt(tooltipDivStyle.padding, 10);
  2686. // Add border styling from options to the style
  2687. tooltipDivStyle = merge(tooltipDivStyle, {
  2688. padding: padding + PX,
  2689. 'background-color': options.backgroundColor,
  2690. 'border-style': 'solid',
  2691. 'border-width': borderWidth + PX,
  2692. 'border-radius': options.borderRadius + PX
  2693. });
  2694. // Optionally add shadow
  2695. if (options.shadow) {
  2696. tooltipDivStyle = merge(tooltipDivStyle, {
  2697. 'box-shadow': '1px 1px 3px gray', // w3c
  2698. '-webkit-box-shadow': '1px 1px 3px gray' // webkit
  2699. });
  2700. }
  2701. css(tooltipDiv, tooltipDivStyle);
  2702. // Set simple style on the line
  2703. css(tooltipLine, {
  2704. 'border-left': '1px solid darkgray'
  2705. });
  2706. // This event is triggered when a new tooltip should be shown
  2707. addEvent(chart, 'tooltipRefresh', function (args) {
  2708. var chartContainer = chart.container,
  2709. offsetLeft = chartContainer.offsetLeft,
  2710. offsetTop = chartContainer.offsetTop,
  2711. position;
  2712. // Set the content of the tooltip
  2713. tooltipDiv.innerHTML = args.text;
  2714. // Compute the best position for the tooltip based on the divs size and container size.
  2715. position = chart.tooltip.getPosition(tooltipDiv.offsetWidth, tooltipDiv.offsetHeight, {
  2716. plotX: args.x,
  2717. plotY: args.y
  2718. });
  2719. css(tooltipDiv, {
  2720. visibility: VISIBLE,
  2721. left: position.x + PX,
  2722. top: position.y + PX,
  2723. 'border-color': args.borderColor
  2724. });
  2725. // Position the tooltip line
  2726. css(tooltipLine, {
  2727. visibility: VISIBLE,
  2728. left: offsetLeft + args.x + PX,
  2729. top: offsetTop + chart.plotTop + PX,
  2730. height: chart.plotHeight + PX
  2731. });
  2732. // This timeout hides the tooltip after 3 seconds
  2733. // First clear any existing timer
  2734. if (renderer.ttTimer !== UNDEFINED) {
  2735. clearTimeout(renderer.ttTimer);
  2736. }
  2737. // Start a new timer that hides tooltip and line
  2738. renderer.ttTimer = setTimeout(function () {
  2739. css(tooltipDiv, {visibility: HIDDEN});
  2740. css(tooltipLine, {visibility: HIDDEN});
  2741. }, 3000);
  2742. });
  2743. },
  2744. /**
  2745. * Extend SVGRenderer.destroy to also destroy the elements added by CanVGRenderer.
  2746. */
  2747. destroy: function () {
  2748. var renderer = this;
  2749. // Remove the canvas
  2750. discardElement(renderer.canvas);
  2751. // Kill the timer
  2752. if (renderer.ttTimer !== UNDEFINED) {
  2753. clearTimeout(renderer.ttTimer);
  2754. }
  2755. // Remove the divs for tooltip and line
  2756. discardElement(renderer.ttLine);
  2757. discardElement(renderer.ttDiv);
  2758. discardElement(renderer.hiddenSvg);
  2759. // Continue with base class
  2760. return SVGRenderer.prototype.destroy.apply(renderer);
  2761. },
  2762. /**
  2763. * Take a color and return it if it's a string, do not make it a gradient even if it is a
  2764. * gradient. Currently canvg cannot render gradients (turns out black),
  2765. * see: http://code.google.com/p/canvg/issues/detail?id=104
  2766. *
  2767. * @param {Object} color The color or config object
  2768. */
  2769. color: function (color, elem, prop) {
  2770. if (color && color.linearGradient) {
  2771. // Pick the end color and forward to base implementation
  2772. color = color.stops[color.stops.length - 1][1];
  2773. }
  2774. return SVGRenderer.prototype.color.call(this, color, elem, prop);
  2775. },
  2776. /**
  2777. * Draws the SVG on the canvas or adds a draw invokation to the deferred list.
  2778. */
  2779. draw: function () {
  2780. var renderer = this;
  2781. window.canvg(renderer.canvas, renderer.hiddenSvg.innerHTML);
  2782. }
  2783. });
  2784. }(Highcharts));