canvg.js 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  1. /*
  2. * canvg.js - Javascript SVG parser and renderer on Canvas
  3. * MIT Licensed
  4. * Gabe Lerner (gabelerner@gmail.com)
  5. * http://code.google.com/p/canvg/
  6. *
  7. * Requires: rgbcolor.js - http://www.phpied.com/rgb-color-parser-in-javascript/
  8. */
  9. if(!window.console) {
  10. window.console = {};
  11. window.console.log = function(str) {};
  12. window.console.dir = function(str) {};
  13. }
  14. // <3 IE
  15. if(!Array.indexOf){
  16. Array.prototype.indexOf = function(obj){
  17. for(var i=0; i<this.length; i++){
  18. if(this[i]==obj){
  19. return i;
  20. }
  21. }
  22. return -1;
  23. }
  24. }
  25. (function(){
  26. // canvg(target, s)
  27. // target: canvas element or the id of a canvas element
  28. // s: svg string or url to svg file
  29. // opts: optional hash of options
  30. // ignoreMouse: true => ignore mouse events
  31. // ignoreAnimation: true => ignore animations
  32. // renderCallback: function => will call the function after the first render is completed
  33. // forceRedraw: function => will call the function on every frame, if it returns true, will redraw
  34. this.canvg = function (target, s, opts) {
  35. if (typeof target == 'string') {
  36. target = document.getElementById(target);
  37. }
  38. // reuse class per canvas
  39. var svg;
  40. if (target.svg == null) {
  41. svg = build();
  42. target.svg = svg;
  43. }
  44. else {
  45. svg = target.svg;
  46. svg.stop();
  47. }
  48. svg.opts = opts;
  49. var ctx = target.getContext('2d');
  50. if (s.substr(0,1) == '<') {
  51. // load from xml string
  52. svg.loadXml(ctx, s);
  53. }
  54. else {
  55. // load from url
  56. svg.load(ctx, s);
  57. }
  58. }
  59. function build() {
  60. var svg = { };
  61. svg.FRAMERATE = 30;
  62. // globals
  63. svg.init = function(ctx) {
  64. svg.Definitions = {};
  65. svg.Styles = {};
  66. svg.Animations = [];
  67. svg.Images = [];
  68. svg.ctx = ctx;
  69. svg.ViewPort = new (function () {
  70. this.viewPorts = [];
  71. this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); }
  72. this.RemoveCurrent = function() { this.viewPorts.pop(); }
  73. this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; }
  74. this.width = function() { return this.Current().width; }
  75. this.height = function() { return this.Current().height; }
  76. this.ComputeSize = function(d) {
  77. if (d != null && typeof(d) == 'number') return d;
  78. if (d == 'x') return this.width();
  79. if (d == 'y') return this.height();
  80. return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2);
  81. }
  82. });
  83. }
  84. svg.init();
  85. // images loaded
  86. svg.ImagesLoaded = function() {
  87. for (var i=0; i<svg.Images.length; i++) {
  88. if (!svg.Images[i].loaded) return false;
  89. }
  90. return true;
  91. }
  92. // trim
  93. svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); }
  94. // compress spaces
  95. svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); }
  96. // ajax
  97. svg.ajax = function(url) {
  98. var AJAX;
  99. if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();}
  100. else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');}
  101. if(AJAX){
  102. AJAX.open('GET',url,false);
  103. AJAX.send(null);
  104. return AJAX.responseText;
  105. }
  106. return null;
  107. }
  108. // parse xml
  109. svg.parseXml = function(xml) {
  110. if (window.DOMParser)
  111. {
  112. var parser = new DOMParser();
  113. return parser.parseFromString(xml, 'text/xml');
  114. }
  115. else
  116. {
  117. xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
  118. var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
  119. xmlDoc.async = 'false';
  120. xmlDoc.loadXML(xml);
  121. return xmlDoc;
  122. }
  123. }
  124. svg.Property = function(name, value) {
  125. this.name = name;
  126. this.value = value;
  127. this.hasValue = function() {
  128. return (this.value != null && this.value != '');
  129. }
  130. // return the numerical value of the property
  131. this.numValue = function() {
  132. if (!this.hasValue()) return 0;
  133. var n = parseFloat(this.value);
  134. if ((this.value + '').match(/%$/)) {
  135. n = n / 100.0;
  136. }
  137. return n;
  138. }
  139. this.valueOrDefault = function(def) {
  140. if (this.hasValue()) return this.value;
  141. return def;
  142. }
  143. this.numValueOrDefault = function(def) {
  144. if (this.hasValue()) return this.numValue();
  145. return def;
  146. }
  147. /* EXTENSIONS */
  148. var that = this;
  149. // color extensions
  150. this.Color = {
  151. // augment the current color value with the opacity
  152. addOpacity: function(opacity) {
  153. var newValue = that.value;
  154. if (opacity != null && opacity != '') {
  155. var color = new RGBColor(that.value);
  156. if (color.ok) {
  157. newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')';
  158. }
  159. }
  160. return new svg.Property(that.name, newValue);
  161. }
  162. }
  163. // definition extensions
  164. this.Definition = {
  165. // get the definition from the definitions table
  166. getDefinition: function() {
  167. var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2');
  168. return svg.Definitions[name];
  169. },
  170. isUrl: function() {
  171. return that.value.indexOf('url(') == 0
  172. },
  173. getFillStyle: function(e) {
  174. var def = this.getDefinition();
  175. // gradient
  176. if (def != null && def.createGradient) {
  177. return def.createGradient(svg.ctx, e);
  178. }
  179. // pattern
  180. if (def != null && def.createPattern) {
  181. return def.createPattern(svg.ctx, e);
  182. }
  183. return null;
  184. }
  185. }
  186. // length extensions
  187. this.Length = {
  188. DPI: function(viewPort) {
  189. return 96.0; // TODO: compute?
  190. },
  191. EM: function(viewPort) {
  192. var em = 12;
  193. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  194. if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort);
  195. return em;
  196. },
  197. // get the length as pixels
  198. toPixels: function(viewPort) {
  199. if (!that.hasValue()) return 0;
  200. var s = that.value+'';
  201. if (s.match(/em$/)) return that.numValue() * this.EM(viewPort);
  202. if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0;
  203. if (s.match(/px$/)) return that.numValue();
  204. if (s.match(/pt$/)) return that.numValue() * 1.25;
  205. if (s.match(/pc$/)) return that.numValue() * 15;
  206. if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54;
  207. if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4;
  208. if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort);
  209. if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort);
  210. return that.numValue();
  211. }
  212. }
  213. // time extensions
  214. this.Time = {
  215. // get the time as milliseconds
  216. toMilliseconds: function() {
  217. if (!that.hasValue()) return 0;
  218. var s = that.value+'';
  219. if (s.match(/s$/)) return that.numValue() * 1000;
  220. if (s.match(/ms$/)) return that.numValue();
  221. return that.numValue();
  222. }
  223. }
  224. // angle extensions
  225. this.Angle = {
  226. // get the angle as radians
  227. toRadians: function() {
  228. if (!that.hasValue()) return 0;
  229. var s = that.value+'';
  230. if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0);
  231. if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0);
  232. if (s.match(/rad$/)) return that.numValue();
  233. return that.numValue() * (Math.PI / 180.0);
  234. }
  235. }
  236. }
  237. // fonts
  238. svg.Font = new (function() {
  239. this.Styles = ['normal','italic','oblique','inherit'];
  240. this.Variants = ['normal','small-caps','inherit'];
  241. this.Weights = ['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','inherit'];
  242. this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) {
  243. var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font);
  244. return {
  245. fontFamily: fontFamily || f.fontFamily,
  246. fontSize: fontSize || f.fontSize,
  247. fontStyle: fontStyle || f.fontStyle,
  248. fontWeight: fontWeight || f.fontWeight,
  249. fontVariant: fontVariant || f.fontVariant,
  250. toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') }
  251. }
  252. }
  253. var that = this;
  254. this.Parse = function(s) {
  255. var f = {};
  256. var d = svg.trim(svg.compressSpaces(s || '')).split(' ');
  257. var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false }
  258. var ff = '';
  259. for (var i=0; i<d.length; i++) {
  260. if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; }
  261. else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; }
  262. else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontWeight = d[i]; set.fontStyle = set.fontVariant = set.fontWeight = true; }
  263. else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; }
  264. else { if (d[i] != 'inherit') ff += d[i]; }
  265. } if (ff != '') f.fontFamily = ff;
  266. return f;
  267. }
  268. });
  269. // points and paths
  270. svg.ToNumberArray = function(s) {
  271. var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' ');
  272. for (var i=0; i<a.length; i++) {
  273. a[i] = parseFloat(a[i]);
  274. }
  275. return a;
  276. }
  277. svg.Point = function(x, y) {
  278. this.x = x;
  279. this.y = y;
  280. this.angleTo = function(p) {
  281. return Math.atan2(p.y - this.y, p.x - this.x);
  282. }
  283. this.applyTransform = function(v) {
  284. var xp = this.x * v[0] + this.y * v[2] + v[4];
  285. var yp = this.x * v[1] + this.y * v[3] + v[5];
  286. this.x = xp;
  287. this.y = yp;
  288. }
  289. }
  290. svg.CreatePoint = function(s) {
  291. var a = svg.ToNumberArray(s);
  292. return new svg.Point(a[0], a[1]);
  293. }
  294. svg.CreatePath = function(s) {
  295. var a = svg.ToNumberArray(s);
  296. var path = [];
  297. for (var i=0; i<a.length; i+=2) {
  298. path.push(new svg.Point(a[i], a[i+1]));
  299. }
  300. return path;
  301. }
  302. // bounding box
  303. svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want
  304. this.x1 = Number.NaN;
  305. this.y1 = Number.NaN;
  306. this.x2 = Number.NaN;
  307. this.y2 = Number.NaN;
  308. this.x = function() { return this.x1; }
  309. this.y = function() { return this.y1; }
  310. this.width = function() { return this.x2 - this.x1; }
  311. this.height = function() { return this.y2 - this.y1; }
  312. this.addPoint = function(x, y) {
  313. if (x != null) {
  314. if (isNaN(this.x1) || isNaN(this.x2)) {
  315. this.x1 = x;
  316. this.x2 = x;
  317. }
  318. if (x < this.x1) this.x1 = x;
  319. if (x > this.x2) this.x2 = x;
  320. }
  321. if (y != null) {
  322. if (isNaN(this.y1) || isNaN(this.y2)) {
  323. this.y1 = y;
  324. this.y2 = y;
  325. }
  326. if (y < this.y1) this.y1 = y;
  327. if (y > this.y2) this.y2 = y;
  328. }
  329. }
  330. this.addX = function(x) { this.addPoint(x, null); }
  331. this.addY = function(y) { this.addPoint(null, y); }
  332. this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) {
  333. var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0)
  334. var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0)
  335. var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0)
  336. var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0)
  337. this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y);
  338. }
  339. this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
  340. // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
  341. var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y];
  342. this.addPoint(p0[0], p0[1]);
  343. this.addPoint(p3[0], p3[1]);
  344. for (i=0; i<=1; i++) {
  345. var f = function(t) {
  346. return Math.pow(1-t, 3) * p0[i]
  347. + 3 * Math.pow(1-t, 2) * t * p1[i]
  348. + 3 * (1-t) * Math.pow(t, 2) * p2[i]
  349. + Math.pow(t, 3) * p3[i];
  350. }
  351. var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
  352. var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
  353. var c = 3 * p1[i] - 3 * p0[i];
  354. if (a == 0) {
  355. if (b == 0) continue;
  356. var t = -c / b;
  357. if (0 < t && t < 1) {
  358. if (i == 0) this.addX(f(t));
  359. if (i == 1) this.addY(f(t));
  360. }
  361. continue;
  362. }
  363. var b2ac = Math.pow(b, 2) - 4 * c * a;
  364. if (b2ac < 0) continue;
  365. var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
  366. if (0 < t1 && t1 < 1) {
  367. if (i == 0) this.addX(f(t1));
  368. if (i == 1) this.addY(f(t1));
  369. }
  370. var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
  371. if (0 < t2 && t2 < 1) {
  372. if (i == 0) this.addX(f(t2));
  373. if (i == 1) this.addY(f(t2));
  374. }
  375. }
  376. }
  377. this.isPointInBox = function(x, y) {
  378. return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2);
  379. }
  380. this.addPoint(x1, y1);
  381. this.addPoint(x2, y2);
  382. }
  383. // transforms
  384. svg.Transform = function(v) {
  385. var that = this;
  386. this.Type = {}
  387. // translate
  388. this.Type.translate = function(s) {
  389. this.p = svg.CreatePoint(s);
  390. this.apply = function(ctx) {
  391. ctx.translate(this.p.x || 0.0, this.p.y || 0.0);
  392. }
  393. this.applyToPoint = function(p) {
  394. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  395. }
  396. }
  397. // rotate
  398. this.Type.rotate = function(s) {
  399. var a = svg.ToNumberArray(s);
  400. this.angle = new svg.Property('angle', a[0]);
  401. this.cx = a[1] || 0;
  402. this.cy = a[2] || 0;
  403. this.apply = function(ctx) {
  404. ctx.translate(this.cx, this.cy);
  405. ctx.rotate(this.angle.Angle.toRadians());
  406. ctx.translate(-this.cx, -this.cy);
  407. }
  408. this.applyToPoint = function(p) {
  409. var a = this.angle.Angle.toRadians();
  410. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  411. p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]);
  412. p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]);
  413. }
  414. }
  415. this.Type.scale = function(s) {
  416. this.p = svg.CreatePoint(s);
  417. this.apply = function(ctx) {
  418. ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0);
  419. }
  420. this.applyToPoint = function(p) {
  421. p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]);
  422. }
  423. }
  424. this.Type.matrix = function(s) {
  425. this.m = svg.ToNumberArray(s);
  426. this.apply = function(ctx) {
  427. ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
  428. }
  429. this.applyToPoint = function(p) {
  430. p.applyTransform(this.m);
  431. }
  432. }
  433. this.Type.SkewBase = function(s) {
  434. this.base = that.Type.matrix;
  435. this.base(s);
  436. this.angle = new svg.Property('angle', s);
  437. }
  438. this.Type.SkewBase.prototype = new this.Type.matrix;
  439. this.Type.skewX = function(s) {
  440. this.base = that.Type.SkewBase;
  441. this.base(s);
  442. this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0];
  443. }
  444. this.Type.skewX.prototype = new this.Type.SkewBase;
  445. this.Type.skewY = function(s) {
  446. this.base = that.Type.SkewBase;
  447. this.base(s);
  448. this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0];
  449. }
  450. this.Type.skewY.prototype = new this.Type.SkewBase;
  451. this.transforms = [];
  452. this.apply = function(ctx) {
  453. for (var i=0; i<this.transforms.length; i++) {
  454. this.transforms[i].apply(ctx);
  455. }
  456. }
  457. this.applyToPoint = function(p) {
  458. for (var i=0; i<this.transforms.length; i++) {
  459. this.transforms[i].applyToPoint(p);
  460. }
  461. }
  462. var data = v.split(/\s(?=[a-z])/);
  463. for (var i=0; i<data.length; i++) {
  464. var type = data[i].split('(')[0];
  465. var s = data[i].split('(')[1].replace(')','');
  466. var transform = eval('new this.Type.' + type + '(s)');
  467. this.transforms.push(transform);
  468. }
  469. }
  470. // aspect ratio
  471. svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {
  472. // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
  473. aspectRatio = svg.compressSpaces(aspectRatio);
  474. aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer
  475. var align = aspectRatio.split(' ')[0] || 'xMidYMid';
  476. var meetOrSlice = aspectRatio.split(' ')[1] || 'meet';
  477. // calculate scale
  478. var scaleX = width / desiredWidth;
  479. var scaleY = height / desiredHeight;
  480. var scaleMin = Math.min(scaleX, scaleY);
  481. var scaleMax = Math.max(scaleX, scaleY);
  482. if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; }
  483. if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; }
  484. refX = new svg.Property('refX', refX);
  485. refY = new svg.Property('refY', refY);
  486. if (refX.hasValue() && refY.hasValue()) {
  487. ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y'));
  488. }
  489. else {
  490. // align
  491. if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);
  492. if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);
  493. if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0);
  494. if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight);
  495. }
  496. // scale
  497. if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin);
  498. if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax);
  499. // translate
  500. ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);
  501. }
  502. // elements
  503. svg.Element = {}
  504. svg.Element.ElementBase = function(node) {
  505. this.attributes = {};
  506. this.styles = {};
  507. this.children = [];
  508. // get or create attribute
  509. this.attribute = function(name, createIfNotExists) {
  510. var a = this.attributes[name];
  511. if (a != null) return a;
  512. a = new svg.Property(name, '');
  513. if (createIfNotExists == true) this.attributes[name] = a;
  514. return a;
  515. }
  516. // get or create style
  517. this.style = function(name, createIfNotExists) {
  518. var s = this.styles[name];
  519. if (s != null) return s;
  520. var a = this.attribute(name);
  521. if (a != null && a.hasValue()) {
  522. return a;
  523. }
  524. s = new svg.Property(name, '');
  525. if (createIfNotExists == true) this.styles[name] = s;
  526. return s;
  527. }
  528. // base render
  529. this.render = function(ctx) {
  530. // don't render display=none
  531. if (this.attribute('display').value == 'none') return;
  532. ctx.save();
  533. this.setContext(ctx);
  534. this.renderChildren(ctx);
  535. this.clearContext(ctx);
  536. ctx.restore();
  537. }
  538. // base set context
  539. this.setContext = function(ctx) {
  540. // OVERRIDE ME!
  541. }
  542. // base clear context
  543. this.clearContext = function(ctx) {
  544. // OVERRIDE ME!
  545. }
  546. // base render children
  547. this.renderChildren = function(ctx) {
  548. for (var i=0; i<this.children.length; i++) {
  549. this.children[i].render(ctx);
  550. }
  551. }
  552. this.addChild = function(childNode, create) {
  553. var child = childNode;
  554. if (create) child = svg.CreateElement(childNode);
  555. child.parent = this;
  556. this.children.push(child);
  557. }
  558. if (node != null && node.nodeType == 1) { //ELEMENT_NODE
  559. // add children
  560. for (var i=0; i<node.childNodes.length; i++) {
  561. var childNode = node.childNodes[i];
  562. if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE
  563. }
  564. // add attributes
  565. for (var i=0; i<node.attributes.length; i++) {
  566. var attribute = node.attributes[i];
  567. this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue);
  568. }
  569. // add tag styles
  570. var styles = svg.Styles[this.type];
  571. if (styles != null) {
  572. for (var name in styles) {
  573. this.styles[name] = styles[name];
  574. }
  575. }
  576. // add class styles
  577. if (this.attribute('class').hasValue()) {
  578. var classes = svg.compressSpaces(this.attribute('class').value).split(' ');
  579. for (var j=0; j<classes.length; j++) {
  580. styles = svg.Styles['.'+classes[j]];
  581. if (styles != null) {
  582. for (var name in styles) {
  583. this.styles[name] = styles[name];
  584. }
  585. }
  586. }
  587. }
  588. // add inline styles
  589. if (this.attribute('style').hasValue()) {
  590. var styles = this.attribute('style').value.split(';');
  591. for (var i=0; i<styles.length; i++) {
  592. if (svg.trim(styles[i]) != '') {
  593. var style = styles[i].split(':');
  594. var name = svg.trim(style[0]);
  595. var value = svg.trim(style[1]);
  596. this.styles[name] = new svg.Property(name, value);
  597. }
  598. }
  599. }
  600. // add id
  601. if (this.attribute('id').hasValue()) {
  602. if (svg.Definitions[this.attribute('id').value] == null) {
  603. svg.Definitions[this.attribute('id').value] = this;
  604. }
  605. }
  606. }
  607. }
  608. svg.Element.RenderedElementBase = function(node) {
  609. this.base = svg.Element.ElementBase;
  610. this.base(node);
  611. this.setContext = function(ctx) {
  612. // fill
  613. if (this.style('fill').Definition.isUrl()) {
  614. var fs = this.style('fill').Definition.getFillStyle(this);
  615. if (fs != null) ctx.fillStyle = fs;
  616. }
  617. else if (this.style('fill').hasValue()) {
  618. var fillStyle = this.style('fill');
  619. if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value);
  620. ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);
  621. }
  622. // stroke
  623. if (this.style('stroke').Definition.isUrl()) {
  624. var fs = this.style('stroke').Definition.getFillStyle(this);
  625. if (fs != null) ctx.strokeStyle = fs;
  626. }
  627. else if (this.style('stroke').hasValue()) {
  628. var strokeStyle = this.style('stroke');
  629. if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value);
  630. ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);
  631. }
  632. if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels();
  633. if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;
  634. if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;
  635. if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;
  636. // font
  637. if (typeof(ctx.font) != 'undefined') {
  638. ctx.font = svg.Font.CreateFont(
  639. this.style('font-style').value,
  640. this.style('font-variant').value,
  641. this.style('font-weight').value,
  642. this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '',
  643. this.style('font-family').value).toString();
  644. }
  645. // transform
  646. if (this.attribute('transform').hasValue()) {
  647. var transform = new svg.Transform(this.attribute('transform').value);
  648. transform.apply(ctx);
  649. }
  650. // clip
  651. if (this.attribute('clip-path').hasValue()) {
  652. var clip = this.attribute('clip-path').Definition.getDefinition();
  653. if (clip != null) clip.apply(ctx);
  654. }
  655. // opacity
  656. if (this.style('opacity').hasValue()) {
  657. ctx.globalAlpha = this.style('opacity').numValue();
  658. }
  659. }
  660. }
  661. svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase;
  662. svg.Element.PathElementBase = function(node) {
  663. this.base = svg.Element.RenderedElementBase;
  664. this.base(node);
  665. this.path = function(ctx) {
  666. if (ctx != null) ctx.beginPath();
  667. return new svg.BoundingBox();
  668. }
  669. this.renderChildren = function(ctx) {
  670. this.path(ctx);
  671. svg.Mouse.checkPath(this, ctx);
  672. if (ctx.fillStyle != '') ctx.fill();
  673. if (ctx.strokeStyle != '') ctx.stroke();
  674. var markers = this.getMarkers();
  675. if (markers != null) {
  676. if (this.attribute('marker-start').Definition.isUrl()) {
  677. var marker = this.attribute('marker-start').Definition.getDefinition();
  678. marker.render(ctx, markers[0][0], markers[0][1]);
  679. }
  680. if (this.attribute('marker-mid').Definition.isUrl()) {
  681. var marker = this.attribute('marker-mid').Definition.getDefinition();
  682. for (var i=1;i<markers.length-1;i++) {
  683. marker.render(ctx, markers[i][0], markers[i][1]);
  684. }
  685. }
  686. if (this.attribute('marker-end').Definition.isUrl()) {
  687. var marker = this.attribute('marker-end').Definition.getDefinition();
  688. marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]);
  689. }
  690. }
  691. }
  692. this.getBoundingBox = function() {
  693. return this.path();
  694. }
  695. this.getMarkers = function() {
  696. return null;
  697. }
  698. }
  699. svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase;
  700. // svg element
  701. svg.Element.svg = function(node) {
  702. this.base = svg.Element.RenderedElementBase;
  703. this.base(node);
  704. this.baseClearContext = this.clearContext;
  705. this.clearContext = function(ctx) {
  706. this.baseClearContext(ctx);
  707. svg.ViewPort.RemoveCurrent();
  708. }
  709. this.baseSetContext = this.setContext;
  710. this.setContext = function(ctx) {
  711. this.baseSetContext(ctx);
  712. // create new view port
  713. if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {
  714. ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y'));
  715. }
  716. var width = svg.ViewPort.width();
  717. var height = svg.ViewPort.height();
  718. if (this.attribute('width').hasValue() && this.attribute('height').hasValue()) {
  719. width = this.attribute('width').Length.toPixels('x');
  720. height = this.attribute('height').Length.toPixels('y');
  721. var x = 0;
  722. var y = 0;
  723. if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {
  724. x = -this.attribute('refX').Length.toPixels('x');
  725. y = -this.attribute('refY').Length.toPixels('y');
  726. }
  727. ctx.beginPath();
  728. ctx.moveTo(x, y);
  729. ctx.lineTo(width, y);
  730. ctx.lineTo(width, height);
  731. ctx.lineTo(x, height);
  732. ctx.closePath();
  733. ctx.clip();
  734. }
  735. svg.ViewPort.SetCurrent(width, height);
  736. // viewbox
  737. if (this.attribute('viewBox').hasValue()) {
  738. var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
  739. var minX = viewBox[0];
  740. var minY = viewBox[1];
  741. width = viewBox[2];
  742. height = viewBox[3];
  743. svg.AspectRatio(ctx,
  744. this.attribute('preserveAspectRatio').value,
  745. svg.ViewPort.width(),
  746. width,
  747. svg.ViewPort.height(),
  748. height,
  749. minX,
  750. minY,
  751. this.attribute('refX').value,
  752. this.attribute('refY').value);
  753. svg.ViewPort.RemoveCurrent();
  754. svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
  755. }
  756. // initial values
  757. ctx.strokeStyle = 'rgba(0,0,0,0)';
  758. ctx.lineCap = 'butt';
  759. ctx.lineJoin = 'miter';
  760. ctx.miterLimit = 4;
  761. }
  762. }
  763. svg.Element.svg.prototype = new svg.Element.RenderedElementBase;
  764. // rect element
  765. svg.Element.rect = function(node) {
  766. this.base = svg.Element.PathElementBase;
  767. this.base(node);
  768. this.path = function(ctx) {
  769. var x = this.attribute('x').Length.toPixels('x');
  770. var y = this.attribute('y').Length.toPixels('y');
  771. var width = this.attribute('width').Length.toPixels('x');
  772. var height = this.attribute('height').Length.toPixels('y');
  773. var rx = this.attribute('rx').Length.toPixels('x');
  774. var ry = this.attribute('ry').Length.toPixels('y');
  775. if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;
  776. if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;
  777. if (ctx != null) {
  778. ctx.beginPath();
  779. ctx.moveTo(x + rx, y);
  780. ctx.lineTo(x + width - rx, y);
  781. ctx.quadraticCurveTo(x + width, y, x + width, y + ry)
  782. ctx.lineTo(x + width, y + height - ry);
  783. ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height)
  784. ctx.lineTo(x + rx, y + height);
  785. ctx.quadraticCurveTo(x, y + height, x, y + height - ry)
  786. ctx.lineTo(x, y + ry);
  787. ctx.quadraticCurveTo(x, y, x + rx, y)
  788. ctx.closePath();
  789. }
  790. return new svg.BoundingBox(x, y, x + width, y + height);
  791. }
  792. }
  793. svg.Element.rect.prototype = new svg.Element.PathElementBase;
  794. // circle element
  795. svg.Element.circle = function(node) {
  796. this.base = svg.Element.PathElementBase;
  797. this.base(node);
  798. this.path = function(ctx) {
  799. var cx = this.attribute('cx').Length.toPixels('x');
  800. var cy = this.attribute('cy').Length.toPixels('y');
  801. var r = this.attribute('r').Length.toPixels();
  802. if (ctx != null) {
  803. ctx.beginPath();
  804. ctx.arc(cx, cy, r, 0, Math.PI * 2, true);
  805. ctx.closePath();
  806. }
  807. return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);
  808. }
  809. }
  810. svg.Element.circle.prototype = new svg.Element.PathElementBase;
  811. // ellipse element
  812. svg.Element.ellipse = function(node) {
  813. this.base = svg.Element.PathElementBase;
  814. this.base(node);
  815. this.path = function(ctx) {
  816. var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
  817. var rx = this.attribute('rx').Length.toPixels('x');
  818. var ry = this.attribute('ry').Length.toPixels('y');
  819. var cx = this.attribute('cx').Length.toPixels('x');
  820. var cy = this.attribute('cy').Length.toPixels('y');
  821. if (ctx != null) {
  822. ctx.beginPath();
  823. ctx.moveTo(cx, cy - ry);
  824. ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);
  825. ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);
  826. ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);
  827. ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);
  828. ctx.closePath();
  829. }
  830. return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);
  831. }
  832. }
  833. svg.Element.ellipse.prototype = new svg.Element.PathElementBase;
  834. // line element
  835. svg.Element.line = function(node) {
  836. this.base = svg.Element.PathElementBase;
  837. this.base(node);
  838. this.getPoints = function() {
  839. return [
  840. new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')),
  841. new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))];
  842. }
  843. this.path = function(ctx) {
  844. var points = this.getPoints();
  845. if (ctx != null) {
  846. ctx.beginPath();
  847. ctx.moveTo(points[0].x, points[0].y);
  848. ctx.lineTo(points[1].x, points[1].y);
  849. }
  850. return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);
  851. }
  852. this.getMarkers = function() {
  853. var points = this.getPoints();
  854. var a = points[0].angleTo(points[1]);
  855. return [[points[0], a], [points[1], a]];
  856. }
  857. }
  858. svg.Element.line.prototype = new svg.Element.PathElementBase;
  859. // polyline element
  860. svg.Element.polyline = function(node) {
  861. this.base = svg.Element.PathElementBase;
  862. this.base(node);
  863. this.points = svg.CreatePath(this.attribute('points').value);
  864. this.path = function(ctx) {
  865. var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);
  866. if (ctx != null) {
  867. ctx.beginPath();
  868. ctx.moveTo(this.points[0].x, this.points[0].y);
  869. }
  870. for (var i=1; i<this.points.length; i++) {
  871. bb.addPoint(this.points[i].x, this.points[i].y);
  872. if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);
  873. }
  874. return bb;
  875. }
  876. this.getMarkers = function() {
  877. var markers = [];
  878. for (var i=0; i<this.points.length - 1; i++) {
  879. markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]);
  880. }
  881. markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]);
  882. return markers;
  883. }
  884. }
  885. svg.Element.polyline.prototype = new svg.Element.PathElementBase;
  886. // polygon element
  887. svg.Element.polygon = function(node) {
  888. this.base = svg.Element.polyline;
  889. this.base(node);
  890. this.basePath = this.path;
  891. this.path = function(ctx) {
  892. var bb = this.basePath(ctx);
  893. if (ctx != null) {
  894. ctx.lineTo(this.points[0].x, this.points[0].y);
  895. ctx.closePath();
  896. }
  897. return bb;
  898. }
  899. }
  900. svg.Element.polygon.prototype = new svg.Element.polyline;
  901. // path element
  902. svg.Element.path = function(node) {
  903. this.base = svg.Element.PathElementBase;
  904. this.base(node);
  905. var d = this.attribute('d').value;
  906. // TODO: floating points, convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF
  907. d = d.replace(/,/gm,' '); // get rid of all commas
  908. d = d.replace(/([A-Za-z])([A-Za-z])/gm,'$1 $2'); // separate commands from commands
  909. d = d.replace(/([A-Za-z])([A-Za-z])/gm,'$1 $2'); // separate commands from commands
  910. d = d.replace(/([A-Za-z])([^\s])/gm,'$1 $2'); // separate commands from points
  911. d = d.replace(/([^\s])([A-Za-z])/gm,'$1 $2'); // separate commands from points
  912. d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma
  913. d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma
  914. d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax
  915. d = svg.compressSpaces(d); // compress multiple spaces
  916. d = svg.trim(d);
  917. this.PathParser = new (function(d) {
  918. this.tokens = d.split(' ');
  919. this.reset = function() {
  920. this.i = -1;
  921. this.command = '';
  922. this.previousCommand = '';
  923. this.control = new svg.Point(0, 0);
  924. this.current = new svg.Point(0, 0);
  925. this.points = [];
  926. this.angles = [];
  927. }
  928. this.isEnd = function() {
  929. return this.i == this.tokens.length - 1;
  930. }
  931. this.isCommandOrEnd = function() {
  932. if (this.isEnd()) return true;
  933. return this.tokens[this.i + 1].match(/[A-Za-z]/) != null;
  934. }
  935. this.isRelativeCommand = function() {
  936. return this.command == this.command.toLowerCase();
  937. }
  938. this.getToken = function() {
  939. this.i = this.i + 1;
  940. return this.tokens[this.i];
  941. }
  942. this.getScalar = function() {
  943. return parseFloat(this.getToken());
  944. }
  945. this.nextCommand = function() {
  946. this.previousCommand = this.command;
  947. this.command = this.getToken();
  948. }
  949. this.getPoint = function() {
  950. var p = new svg.Point(this.getScalar(), this.getScalar());
  951. return this.makeAbsolute(p);
  952. }
  953. this.getAsControlPoint = function() {
  954. var p = this.getPoint();
  955. this.control = p;
  956. return p;
  957. }
  958. this.getAsCurrentPoint = function() {
  959. var p = this.getPoint();
  960. this.current = p;
  961. return p;
  962. }
  963. this.getReflectedControlPoint = function() {
  964. if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') {
  965. return this.current;
  966. }
  967. // reflect point
  968. var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);
  969. return p;
  970. }
  971. this.makeAbsolute = function(p) {
  972. if (this.isRelativeCommand()) {
  973. p.x = this.current.x + p.x;
  974. p.y = this.current.y + p.y;
  975. }
  976. return p;
  977. }
  978. this.addMarker = function(p, from) {
  979. this.addMarkerAngle(p, from == null ? null : from.angleTo(p));
  980. }
  981. this.addMarkerAngle = function(p, a) {
  982. this.points.push(p);
  983. this.angles.push(a);
  984. }
  985. this.getMarkerPoints = function() { return this.points; }
  986. this.getMarkerAngles = function() {
  987. for (var i=0; i<this.angles.length; i++) {
  988. if (this.angles[i] == null) {
  989. for (var j=i+1; j<this.angles.length; j++) {
  990. if (this.angles[j] != null) {
  991. this.angles[i] = this.angles[j];
  992. break;
  993. }
  994. }
  995. }
  996. }
  997. return this.angles;
  998. }
  999. })(d);
  1000. this.path = function(ctx) {
  1001. var pp = this.PathParser;
  1002. pp.reset();
  1003. var bb = new svg.BoundingBox();
  1004. if (ctx != null) ctx.beginPath();
  1005. while (!pp.isEnd()) {
  1006. pp.nextCommand();
  1007. if (pp.command.toUpperCase() == 'M') {
  1008. var p = pp.getAsCurrentPoint();
  1009. pp.addMarker(p);
  1010. bb.addPoint(p.x, p.y);
  1011. if (ctx != null) ctx.moveTo(p.x, p.y);
  1012. while (!pp.isCommandOrEnd()) {
  1013. var p = pp.getAsCurrentPoint();
  1014. pp.addMarker(p);
  1015. bb.addPoint(p.x, p.y);
  1016. if (ctx != null) ctx.lineTo(p.x, p.y);
  1017. }
  1018. }
  1019. else if (pp.command.toUpperCase() == 'L') {
  1020. while (!pp.isCommandOrEnd()) {
  1021. var c = pp.current;
  1022. var p = pp.getAsCurrentPoint();
  1023. pp.addMarker(p, c);
  1024. bb.addPoint(p.x, p.y);
  1025. if (ctx != null) ctx.lineTo(p.x, p.y);
  1026. }
  1027. }
  1028. else if (pp.command.toUpperCase() == 'H') {
  1029. while (!pp.isCommandOrEnd()) {
  1030. var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);
  1031. pp.addMarker(newP, pp.current);
  1032. pp.current = newP;
  1033. bb.addPoint(pp.current.x, pp.current.y);
  1034. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1035. }
  1036. }
  1037. else if (pp.command.toUpperCase() == 'V') {
  1038. while (!pp.isCommandOrEnd()) {
  1039. var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
  1040. pp.addMarker(newP, pp.current);
  1041. pp.current = newP;
  1042. bb.addPoint(pp.current.x, pp.current.y);
  1043. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1044. }
  1045. }
  1046. else if (pp.command.toUpperCase() == 'C') {
  1047. while (!pp.isCommandOrEnd()) {
  1048. var curr = pp.current;
  1049. var p1 = pp.getPoint();
  1050. var cntrl = pp.getAsControlPoint();
  1051. var cp = pp.getAsCurrentPoint();
  1052. pp.addMarker(cp, cntrl);
  1053. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1054. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1055. }
  1056. }
  1057. else if (pp.command.toUpperCase() == 'S') {
  1058. while (!pp.isCommandOrEnd()) {
  1059. var curr = pp.current;
  1060. var p1 = pp.getReflectedControlPoint();
  1061. var cntrl = pp.getAsControlPoint();
  1062. var cp = pp.getAsCurrentPoint();
  1063. pp.addMarker(cp, cntrl);
  1064. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1065. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1066. }
  1067. }
  1068. else if (pp.command.toUpperCase() == 'Q') {
  1069. while (!pp.isCommandOrEnd()) {
  1070. var curr = pp.current;
  1071. var cntrl = pp.getAsControlPoint();
  1072. var cp = pp.getAsCurrentPoint();
  1073. pp.addMarker(cp, cntrl);
  1074. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1075. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1076. }
  1077. }
  1078. else if (pp.command.toUpperCase() == 'T') {
  1079. while (!pp.isCommandOrEnd()) {
  1080. var curr = pp.current;
  1081. var cntrl = pp.getReflectedControlPoint();
  1082. pp.control = cntrl;
  1083. var cp = pp.getAsCurrentPoint();
  1084. pp.addMarker(cp, cntrl);
  1085. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1086. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1087. }
  1088. }
  1089. else if (pp.command.toUpperCase() == 'A') {
  1090. while (!pp.isCommandOrEnd()) {
  1091. var curr = pp.current;
  1092. var rx = pp.getScalar();
  1093. var ry = pp.getScalar();
  1094. var xAxisRotation = pp.getScalar() * (Math.PI / 180.0);
  1095. var largeArcFlag = pp.getScalar();
  1096. var sweepFlag = pp.getScalar();
  1097. var cp = pp.getAsCurrentPoint();
  1098. // Conversion from endpoint to center parameterization
  1099. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  1100. // x1', y1'
  1101. var currp = new svg.Point(
  1102. Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,
  1103. -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
  1104. );
  1105. // adjust radii
  1106. var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2);
  1107. if (l > 1) {
  1108. rx *= Math.sqrt(l);
  1109. ry *= Math.sqrt(l);
  1110. }
  1111. // cx', cy'
  1112. var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
  1113. ((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))) /
  1114. (Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2))
  1115. );
  1116. if (isNaN(s)) s = 0;
  1117. var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
  1118. // cx, cy
  1119. var centp = new svg.Point(
  1120. (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
  1121. (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
  1122. );
  1123. // vector magnitude
  1124. var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); }
  1125. // ratio between two vectors
  1126. var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) }
  1127. // angle between two vectors
  1128. var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); }
  1129. // initial angle
  1130. var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]);
  1131. // angle delta
  1132. var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry];
  1133. var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry];
  1134. var ad = a(u, v);
  1135. if (r(u,v) <= -1) ad = Math.PI;
  1136. if (r(u,v) >= 1) ad = 0;
  1137. if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI;
  1138. if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI;
  1139. // for markers
  1140. var halfWay = new svg.Point(
  1141. centp.x - rx * Math.cos((a1 + ad) / 2),
  1142. centp.y - ry * Math.sin((a1 + ad) / 2)
  1143. );
  1144. pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
  1145. pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
  1146. bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better
  1147. if (ctx != null) {
  1148. var r = rx > ry ? rx : ry;
  1149. var sx = rx > ry ? 1 : rx / ry;
  1150. var sy = rx > ry ? ry / rx : 1;
  1151. ctx.translate(centp.x, centp.y);
  1152. ctx.rotate(xAxisRotation);
  1153. ctx.scale(sx, sy);
  1154. ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);
  1155. ctx.scale(1/sx, 1/sy);
  1156. ctx.rotate(-xAxisRotation);
  1157. ctx.translate(-centp.x, -centp.y);
  1158. }
  1159. }
  1160. }
  1161. else if (pp.command.toUpperCase() == 'Z') {
  1162. if (ctx != null) ctx.closePath();
  1163. }
  1164. }
  1165. return bb;
  1166. }
  1167. this.getMarkers = function() {
  1168. var points = this.PathParser.getMarkerPoints();
  1169. var angles = this.PathParser.getMarkerAngles();
  1170. var markers = [];
  1171. for (var i=0; i<points.length; i++) {
  1172. markers.push([points[i], angles[i]]);
  1173. }
  1174. return markers;
  1175. }
  1176. }
  1177. svg.Element.path.prototype = new svg.Element.PathElementBase;
  1178. // pattern element
  1179. svg.Element.pattern = function(node) {
  1180. this.base = svg.Element.ElementBase;
  1181. this.base(node);
  1182. this.createPattern = function(ctx, element) {
  1183. // render me using a temporary svg element
  1184. var tempSvg = new svg.Element.svg();
  1185. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1186. tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value);
  1187. tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value);
  1188. tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);
  1189. tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);
  1190. tempSvg.children = this.children;
  1191. var c = document.createElement('canvas');
  1192. c.width = this.attribute('width').Length.toPixels();
  1193. c.height = this.attribute('height').Length.toPixels();
  1194. tempSvg.render(c.getContext('2d'));
  1195. return ctx.createPattern(c, 'repeat');
  1196. }
  1197. }
  1198. svg.Element.pattern.prototype = new svg.Element.ElementBase;
  1199. // marker element
  1200. svg.Element.marker = function(node) {
  1201. this.base = svg.Element.ElementBase;
  1202. this.base(node);
  1203. this.baseRender = this.render;
  1204. this.render = function(ctx, point, angle) {
  1205. ctx.translate(point.x, point.y);
  1206. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle);
  1207. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);
  1208. ctx.save();
  1209. // render me using a temporary svg element
  1210. var tempSvg = new svg.Element.svg();
  1211. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1212. tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);
  1213. tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);
  1214. tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);
  1215. tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);
  1216. tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));
  1217. tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));
  1218. tempSvg.children = this.children;
  1219. tempSvg.render(ctx);
  1220. ctx.restore();
  1221. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth);
  1222. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle);
  1223. ctx.translate(-point.x, -point.y);
  1224. }
  1225. }
  1226. svg.Element.marker.prototype = new svg.Element.ElementBase;
  1227. // definitions element
  1228. svg.Element.defs = function(node) {
  1229. this.base = svg.Element.ElementBase;
  1230. this.base(node);
  1231. this.render = function(ctx) {
  1232. // NOOP
  1233. }
  1234. }
  1235. svg.Element.defs.prototype = new svg.Element.ElementBase;
  1236. // base for gradients
  1237. svg.Element.GradientBase = function(node) {
  1238. this.base = svg.Element.ElementBase;
  1239. this.base(node);
  1240. this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');
  1241. this.stops = [];
  1242. for (var i=0; i<this.children.length; i++) {
  1243. var child = this.children[i];
  1244. this.stops.push(child);
  1245. }
  1246. this.getGradient = function() {
  1247. // OVERRIDE ME!
  1248. }
  1249. this.createGradient = function(ctx, element) {
  1250. var stopsContainer = this;
  1251. if (this.attribute('xlink:href').hasValue()) {
  1252. stopsContainer = this.attribute('xlink:href').Definition.getDefinition();
  1253. }
  1254. var g = this.getGradient(ctx, element);
  1255. for (var i=0; i<stopsContainer.stops.length; i++) {
  1256. g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color);
  1257. }
  1258. return g;
  1259. }
  1260. }
  1261. svg.Element.GradientBase.prototype = new svg.Element.ElementBase;
  1262. // linear gradient element
  1263. svg.Element.linearGradient = function(node) {
  1264. this.base = svg.Element.GradientBase;
  1265. this.base(node);
  1266. this.getGradient = function(ctx, element) {
  1267. var bb = element.getBoundingBox();
  1268. var x1 = (this.gradientUnits == 'objectBoundingBox'
  1269. ? bb.x() + bb.width() * this.attribute('x1').numValue()
  1270. : this.attribute('x1').Length.toPixels('x'));
  1271. var y1 = (this.gradientUnits == 'objectBoundingBox'
  1272. ? bb.y() + bb.height() * this.attribute('y1').numValue()
  1273. : this.attribute('y1').Length.toPixels('y'));
  1274. var x2 = (this.gradientUnits == 'objectBoundingBox'
  1275. ? bb.x() + bb.width() * this.attribute('x2').numValue()
  1276. : this.attribute('x2').Length.toPixels('x'));
  1277. var y2 = (this.gradientUnits == 'objectBoundingBox'
  1278. ? bb.y() + bb.height() * this.attribute('y2').numValue()
  1279. : this.attribute('y2').Length.toPixels('y'));
  1280. var p1 = new svg.Point(x1, y1);
  1281. var p2 = new svg.Point(x2, y2);
  1282. if (this.attribute('gradientTransform').hasValue()) {
  1283. var transform = new svg.Transform(this.attribute('gradientTransform').value);
  1284. transform.applyToPoint(p1);
  1285. transform.applyToPoint(p2);
  1286. }
  1287. return ctx.createLinearGradient(p1.x, p1.y, p2.x, p2.y);
  1288. }
  1289. }
  1290. svg.Element.linearGradient.prototype = new svg.Element.GradientBase;
  1291. // radial gradient element
  1292. svg.Element.radialGradient = function(node) {
  1293. this.base = svg.Element.GradientBase;
  1294. this.base(node);
  1295. this.getGradient = function(ctx, element) {
  1296. var bb = element.getBoundingBox();
  1297. var cx = (this.gradientUnits == 'objectBoundingBox'
  1298. ? bb.x() + bb.width() * this.attribute('cx').numValue()
  1299. : this.attribute('cx').Length.toPixels('x'));
  1300. var cy = (this.gradientUnits == 'objectBoundingBox'
  1301. ? bb.y() + bb.height() * this.attribute('cy').numValue()
  1302. : this.attribute('cy').Length.toPixels('y'));
  1303. var fx = cx;
  1304. var fy = cy;
  1305. if (this.attribute('fx').hasValue()) {
  1306. fx = (this.gradientUnits == 'objectBoundingBox'
  1307. ? bb.x() + bb.width() * this.attribute('fx').numValue()
  1308. : this.attribute('fx').Length.toPixels('x'));
  1309. }
  1310. if (this.attribute('fy').hasValue()) {
  1311. fy = (this.gradientUnits == 'objectBoundingBox'
  1312. ? bb.y() + bb.height() * this.attribute('fy').numValue()
  1313. : this.attribute('fy').Length.toPixels('y'));
  1314. }
  1315. var r = (this.gradientUnits == 'objectBoundingBox'
  1316. ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue()
  1317. : this.attribute('r').Length.toPixels());
  1318. var c = new svg.Point(cx, cy);
  1319. var f = new svg.Point(fx, fy);
  1320. if (this.attribute('gradientTransform').hasValue()) {
  1321. var transform = new svg.Transform(this.attribute('gradientTransform').value);
  1322. transform.applyToPoint(c);
  1323. transform.applyToPoint(f);
  1324. }
  1325. return ctx.createRadialGradient(f.x, f.y, 0, c.x, c.y, r);
  1326. }
  1327. }
  1328. svg.Element.radialGradient.prototype = new svg.Element.GradientBase;
  1329. // gradient stop element
  1330. svg.Element.stop = function(node) {
  1331. this.base = svg.Element.ElementBase;
  1332. this.base(node);
  1333. this.offset = this.attribute('offset').numValue();
  1334. var stopColor = this.style('stop-color');
  1335. if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value);
  1336. this.color = stopColor.value;
  1337. }
  1338. svg.Element.stop.prototype = new svg.Element.ElementBase;
  1339. // animation base element
  1340. svg.Element.AnimateBase = function(node) {
  1341. this.base = svg.Element.ElementBase;
  1342. this.base(node);
  1343. svg.Animations.push(this);
  1344. this.duration = 0.0;
  1345. this.begin = this.attribute('begin').Time.toMilliseconds();
  1346. this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds();
  1347. this.calcValue = function() {
  1348. // OVERRIDE ME!
  1349. return '';
  1350. }
  1351. this.update = function(delta) {
  1352. // if we're past the end time
  1353. if (this.duration > this.maxDuration) {
  1354. // loop for indefinitely repeating animations
  1355. if (this.attribute('repeatCount').value == 'indefinite') {
  1356. this.duration = 0.0
  1357. }
  1358. else {
  1359. return false; // no updates made
  1360. }
  1361. }
  1362. this.duration = this.duration + delta;
  1363. // if we're past the begin time
  1364. var updated = false;
  1365. if (this.begin < this.duration) {
  1366. var newValue = this.calcValue(); // tween
  1367. var attributeType = this.attribute('attributeType').value;
  1368. var attributeName = this.attribute('attributeName').value;
  1369. if (this.parent != null) {
  1370. if (attributeType == 'CSS') {
  1371. this.parent.style(attributeName, true).value = newValue;
  1372. }
  1373. else { // default or XML
  1374. if (this.attribute('type').hasValue()) {
  1375. // for transform, etc.
  1376. var type = this.attribute('type').value;
  1377. this.parent.attribute(attributeName, true).value = type + '(' + newValue + ')';
  1378. }
  1379. else {
  1380. this.parent.attribute(attributeName, true).value = newValue;
  1381. }
  1382. }
  1383. updated = true;
  1384. }
  1385. }
  1386. return updated;
  1387. }
  1388. // fraction of duration we've covered
  1389. this.progress = function() {
  1390. return ((this.duration - this.begin) / (this.maxDuration - this.begin));
  1391. }
  1392. }
  1393. svg.Element.AnimateBase.prototype = new svg.Element.ElementBase;
  1394. // animate element
  1395. svg.Element.animate = function(node) {
  1396. this.base = svg.Element.AnimateBase;
  1397. this.base(node);
  1398. this.calcValue = function() {
  1399. var from = this.attribute('from').numValue();
  1400. var to = this.attribute('to').numValue();
  1401. // tween value linearly
  1402. return from + (to - from) * this.progress();
  1403. };
  1404. }
  1405. svg.Element.animate.prototype = new svg.Element.AnimateBase;
  1406. // animate color element
  1407. svg.Element.animateColor = function(node) {
  1408. this.base = svg.Element.AnimateBase;
  1409. this.base(node);
  1410. this.calcValue = function() {
  1411. var from = new RGBColor(this.attribute('from').value);
  1412. var to = new RGBColor(this.attribute('to').value);
  1413. if (from.ok && to.ok) {
  1414. // tween color linearly
  1415. var r = from.r + (to.r - from.r) * this.progress();
  1416. var g = from.g + (to.g - from.g) * this.progress();
  1417. var b = from.b + (to.b - from.b) * this.progress();
  1418. return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')';
  1419. }
  1420. return this.attribute('from').value;
  1421. };
  1422. }
  1423. svg.Element.animateColor.prototype = new svg.Element.AnimateBase;
  1424. // animate transform element
  1425. svg.Element.animateTransform = function(node) {
  1426. this.base = svg.Element.animate;
  1427. this.base(node);
  1428. }
  1429. svg.Element.animateTransform.prototype = new svg.Element.animate;
  1430. // text element
  1431. svg.Element.text = function(node) {
  1432. this.base = svg.Element.RenderedElementBase;
  1433. this.base(node);
  1434. if (node != null) {
  1435. // add children
  1436. this.children = [];
  1437. for (var i=0; i<node.childNodes.length; i++) {
  1438. var childNode = node.childNodes[i];
  1439. if (childNode.nodeType == 1) { // capture tspan and tref nodes
  1440. this.addChild(childNode, true);
  1441. }
  1442. else if (childNode.nodeType == 3) { // capture text
  1443. this.addChild(new svg.Element.tspan(childNode), false);
  1444. }
  1445. }
  1446. }
  1447. this.baseSetContext = this.setContext;
  1448. this.setContext = function(ctx) {
  1449. this.baseSetContext(ctx);
  1450. if (this.attribute('text-anchor').hasValue()) {
  1451. var textAnchor = this.attribute('text-anchor').value;
  1452. ctx.textAlign = textAnchor == 'middle' ? 'center' : textAnchor;
  1453. }
  1454. if (this.attribute('alignment-baseline').hasValue()) ctx.textBaseline = this.attribute('alignment-baseline').value;
  1455. }
  1456. this.renderChildren = function(ctx) {
  1457. var x = this.attribute('x').Length.toPixels('x');
  1458. var y = this.attribute('y').Length.toPixels('y');
  1459. for (var i=0; i<this.children.length; i++) {
  1460. var child = this.children[i];
  1461. if (child.attribute('x').hasValue()) {
  1462. child.x = child.attribute('x').Length.toPixels('x');
  1463. }
  1464. else {
  1465. if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x');
  1466. child.x = x;
  1467. x += child.measureText(ctx);
  1468. }
  1469. if (child.attribute('y').hasValue()) {
  1470. child.y = child.attribute('y').Length.toPixels('y');
  1471. }
  1472. else {
  1473. if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y');
  1474. child.y = y;
  1475. }
  1476. child.render(ctx);
  1477. }
  1478. }
  1479. }
  1480. svg.Element.text.prototype = new svg.Element.RenderedElementBase;
  1481. // text base
  1482. svg.Element.TextElementBase = function(node) {
  1483. this.base = svg.Element.RenderedElementBase;
  1484. this.base(node);
  1485. this.renderChildren = function(ctx) {
  1486. ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
  1487. }
  1488. this.getText = function() {
  1489. // OVERRIDE ME
  1490. }
  1491. this.measureText = function(ctx) {
  1492. var textToMeasure = svg.compressSpaces(this.getText());
  1493. if (!ctx.measureText) return textToMeasure.length * 10;
  1494. return ctx.measureText(textToMeasure).width;
  1495. }
  1496. }
  1497. svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase;
  1498. // tspan
  1499. svg.Element.tspan = function(node) {
  1500. this.base = svg.Element.TextElementBase;
  1501. this.base(node);
  1502. // TEXT ELEMENT
  1503. this.text = node.nodeType == 3 ? node.nodeValue : node.childNodes[0].nodeValue;
  1504. this.getText = function() {
  1505. return this.text;
  1506. }
  1507. }
  1508. svg.Element.tspan.prototype = new svg.Element.TextElementBase;
  1509. // tref
  1510. svg.Element.tref = function(node) {
  1511. this.base = svg.Element.TextElementBase;
  1512. this.base(node);
  1513. this.getText = function() {
  1514. var element = this.attribute('xlink:href').Definition.getDefinition();
  1515. if (element != null) return element.children[0].getText();
  1516. }
  1517. }
  1518. svg.Element.tref.prototype = new svg.Element.TextElementBase;
  1519. // a element
  1520. svg.Element.a = function(node) {
  1521. this.base = svg.Element.TextElementBase;
  1522. this.base(node);
  1523. this.hasText = true;
  1524. for (var i=0; i<node.childNodes.length; i++) {
  1525. if (node.childNodes[i].nodeType != 3) this.hasText = false;
  1526. }
  1527. // this might contain text
  1528. this.text = this.hasText ? node.childNodes[0].nodeValue : '';
  1529. this.getText = function() {
  1530. return this.text;
  1531. }
  1532. this.baseRenderChildren = this.renderChildren;
  1533. this.renderChildren = function(ctx) {
  1534. if (this.hasText) {
  1535. // render as text element
  1536. this.baseRenderChildren(ctx);
  1537. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  1538. svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y));
  1539. }
  1540. else {
  1541. // render as temporary group
  1542. var g = new svg.Element.g();
  1543. g.children = this.children;
  1544. g.parent = this;
  1545. g.render(ctx);
  1546. }
  1547. }
  1548. this.onclick = function() {
  1549. window.open(this.attribute('xlink:href').value);
  1550. }
  1551. this.onmousemove = function() {
  1552. svg.ctx.canvas.style.cursor = 'pointer';
  1553. }
  1554. }
  1555. svg.Element.a.prototype = new svg.Element.TextElementBase;
  1556. // image element
  1557. svg.Element.image = function(node) {
  1558. this.base = svg.Element.RenderedElementBase;
  1559. this.base(node);
  1560. svg.Images.push(this);
  1561. this.img = document.createElement('img');
  1562. this.loaded = false;
  1563. var that = this;
  1564. this.img.onload = function() { that.loaded = true; }
  1565. this.img.src = this.attribute('xlink:href').value;
  1566. this.renderChildren = function(ctx) {
  1567. var x = this.attribute('x').Length.toPixels('x');
  1568. var y = this.attribute('y').Length.toPixels('y');
  1569. var width = this.attribute('width').Length.toPixels('x');
  1570. var height = this.attribute('height').Length.toPixels('y');
  1571. if (width == 0 || height == 0) return;
  1572. ctx.save();
  1573. ctx.translate(x, y);
  1574. svg.AspectRatio(ctx,
  1575. this.attribute('preserveAspectRatio').value,
  1576. width,
  1577. this.img.width,
  1578. height,
  1579. this.img.height,
  1580. 0,
  1581. 0);
  1582. ctx.drawImage(this.img, 0, 0);
  1583. ctx.restore();
  1584. }
  1585. }
  1586. svg.Element.image.prototype = new svg.Element.RenderedElementBase;
  1587. // group element
  1588. svg.Element.g = function(node) {
  1589. this.base = svg.Element.RenderedElementBase;
  1590. this.base(node);
  1591. }
  1592. svg.Element.g.prototype = new svg.Element.RenderedElementBase;
  1593. // symbol element
  1594. svg.Element.symbol = function(node) {
  1595. this.base = svg.Element.RenderedElementBase;
  1596. this.base(node);
  1597. }
  1598. svg.Element.symbol.prototype = new svg.Element.RenderedElementBase;
  1599. // style element
  1600. svg.Element.style = function(node) {
  1601. this.base = svg.Element.ElementBase;
  1602. this.base(node);
  1603. var css = node.childNodes[0].nodeValue;
  1604. css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(\/\/.*)/gm, ''); // remove comments
  1605. css = svg.compressSpaces(css); // replace whitespace
  1606. var cssDefs = css.split('}');
  1607. for (var i=0; i<cssDefs.length; i++) {
  1608. if (svg.trim(cssDefs[i]) != '') {
  1609. var cssDef = cssDefs[i].split('{');
  1610. var cssClasses = cssDef[0].split(',');
  1611. var cssProps = cssDef[1].split(';');
  1612. for (var j=0; j<cssClasses.length; j++) {
  1613. var cssClass = svg.trim(cssClasses[j]);
  1614. if (cssClass != '') {
  1615. var props = {};
  1616. for (var k=0; k<cssProps.length; k++) {
  1617. var prop = cssProps[k].split(':');
  1618. var name = prop[0];
  1619. var value = prop[1];
  1620. if (name != null && value != null) {
  1621. props[svg.trim(prop[0])] = new svg.Property(svg.trim(prop[0]), svg.trim(prop[1]));
  1622. }
  1623. }
  1624. svg.Styles[cssClass] = props;
  1625. }
  1626. }
  1627. }
  1628. }
  1629. }
  1630. svg.Element.style.prototype = new svg.Element.ElementBase;
  1631. // use element
  1632. svg.Element.use = function(node) {
  1633. this.base = svg.Element.RenderedElementBase;
  1634. this.base(node);
  1635. this.baseSetContext = this.setContext;
  1636. this.setContext = function(ctx) {
  1637. this.baseSetContext(ctx);
  1638. if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0);
  1639. if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y'));
  1640. }
  1641. this.getDefinition = function() {
  1642. return this.attribute('xlink:href').Definition.getDefinition();
  1643. }
  1644. this.path = function(ctx) {
  1645. var element = this.getDefinition();
  1646. if (element != null) element.path(ctx);
  1647. }
  1648. this.renderChildren = function(ctx) {
  1649. var element = this.getDefinition();
  1650. if (element != null) element.render(ctx);
  1651. }
  1652. }
  1653. svg.Element.use.prototype = new svg.Element.RenderedElementBase;
  1654. // clip element
  1655. svg.Element.clipPath = function(node) {
  1656. this.base = svg.Element.ElementBase;
  1657. this.base(node);
  1658. this.apply = function(ctx) {
  1659. for (var i=0; i<this.children.length; i++) {
  1660. if (this.children[i].path) {
  1661. this.children[i].path(ctx);
  1662. ctx.clip();
  1663. }
  1664. }
  1665. }
  1666. }
  1667. svg.Element.clipPath.prototype = new svg.Element.ElementBase;
  1668. // title element, do nothing
  1669. svg.Element.title = function(node) {
  1670. }
  1671. svg.Element.title.prototype = new svg.Element.ElementBase;
  1672. // desc element, do nothing
  1673. svg.Element.desc = function(node) {
  1674. }
  1675. svg.Element.desc.prototype = new svg.Element.ElementBase;
  1676. svg.Element.MISSING = function(node) {
  1677. console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.');
  1678. }
  1679. svg.Element.MISSING.prototype = new svg.Element.ElementBase;
  1680. // element factory
  1681. svg.CreateElement = function(node) {
  1682. var className = 'svg.Element.' + node.nodeName.replace(/^[^:]+:/,'');
  1683. if (!eval(className)) className = 'svg.Element.MISSING';
  1684. var e = eval('new ' + className + '(node)');
  1685. e.type = node.nodeName;
  1686. return e;
  1687. }
  1688. // load from url
  1689. svg.load = function(ctx, url) {
  1690. svg.loadXml(ctx, svg.ajax(url));
  1691. }
  1692. // load from xml
  1693. svg.loadXml = function(ctx, xml) {
  1694. svg.init(ctx);
  1695. var mapXY = function(p) {
  1696. var e = ctx.canvas;
  1697. while (e) {
  1698. p.x -= e.offsetLeft;
  1699. p.y -= e.offsetTop;
  1700. e = e.offsetParent;
  1701. }
  1702. if (window.scrollX) p.x += window.scrollX;
  1703. if (window.scrollY) p.y += window.scrollY;
  1704. return p;
  1705. }
  1706. // bind mouse
  1707. if (svg.opts == null || svg.opts['ignoreMouse'] != true) {
  1708. ctx.canvas.onclick = function(e) {
  1709. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  1710. svg.Mouse.onclick(p.x, p.y);
  1711. };
  1712. ctx.canvas.onmousemove = function(e) {
  1713. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  1714. svg.Mouse.onmousemove(p.x, p.y);
  1715. };
  1716. }
  1717. var dom = svg.parseXml(xml);
  1718. var e = svg.CreateElement(dom.documentElement);
  1719. // render loop
  1720. var isFirstRender = true;
  1721. var draw = function() {
  1722. // set canvas size
  1723. if (e.style('width').hasValue()) {
  1724. ctx.canvas.width = e.style('width').Length.toPixels(ctx.canvas.parentNode.clientWidth);
  1725. }
  1726. if (e.style('height').hasValue()) {
  1727. ctx.canvas.height = e.style('height').Length.toPixels(ctx.canvas.parentNode.clientHeight);
  1728. }
  1729. svg.ViewPort.SetCurrent(ctx.canvas.clientWidth, ctx.canvas.clientHeight);
  1730. // clear and render
  1731. ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
  1732. e.render(ctx);
  1733. if (isFirstRender) {
  1734. isFirstRender = false;
  1735. if (svg.opts != null && typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback']();
  1736. }
  1737. }
  1738. var waitingForImages = true;
  1739. if (svg.ImagesLoaded()) {
  1740. waitingForImages = false;
  1741. draw();
  1742. }
  1743. svg.intervalID = setInterval(function() {
  1744. var needUpdate = false;
  1745. if (waitingForImages && svg.ImagesLoaded()) {
  1746. waitingForImages = false;
  1747. needUpdate = true;
  1748. }
  1749. // need update from mouse events?
  1750. if (svg.opts == null || svg.opts['ignoreMouse'] != true) {
  1751. needUpdate = needUpdate | svg.Mouse.hasEvents();
  1752. }
  1753. // need update from animations?
  1754. if (svg.opts == null || svg.opts['ignoreAnimation'] != true) {
  1755. for (var i=0; i<svg.Animations.length; i++) {
  1756. needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE);
  1757. }
  1758. }
  1759. // need update from redraw?
  1760. if (svg.opts != null && typeof(svg.opts['forceRedraw']) == 'function') {
  1761. if (svg.opts['forceRedraw']() == true) needUpdate = true;
  1762. }
  1763. // render if needed
  1764. if (needUpdate) {
  1765. draw();
  1766. svg.Mouse.runEvents(); // run and clear our events
  1767. }
  1768. }, 1000 / svg.FRAMERATE);
  1769. }
  1770. svg.stop = function() {
  1771. if (svg.intervalID) {
  1772. clearInterval(svg.intervalID);
  1773. }
  1774. }
  1775. svg.Mouse = new (function() {
  1776. this.events = [];
  1777. this.hasEvents = function() { return this.events.length != 0; }
  1778. this.onclick = function(x, y) {
  1779. this.events.push({ type: 'onclick', x: x, y: y,
  1780. run: function(e) { if (e.onclick) e.onclick(); }
  1781. });
  1782. }
  1783. this.onmousemove = function(x, y) {
  1784. this.events.push({ type: 'onmousemove', x: x, y: y,
  1785. run: function(e) { if (e.onmousemove) e.onmousemove(); }
  1786. });
  1787. }
  1788. this.eventElements = [];
  1789. this.checkPath = function(element, ctx) {
  1790. for (var i=0; i<this.events.length; i++) {
  1791. var e = this.events[i];
  1792. if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;
  1793. }
  1794. }
  1795. this.checkBoundingBox = function(element, bb) {
  1796. for (var i=0; i<this.events.length; i++) {
  1797. var e = this.events[i];
  1798. if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;
  1799. }
  1800. }
  1801. this.runEvents = function() {
  1802. svg.ctx.canvas.style.cursor = '';
  1803. for (var i=0; i<this.events.length; i++) {
  1804. var e = this.events[i];
  1805. var element = this.eventElements[i];
  1806. while (element) {
  1807. e.run(element);
  1808. element = element.parent;
  1809. }
  1810. }
  1811. // done running, clear
  1812. this.events = [];
  1813. this.eventElements = [];
  1814. }
  1815. });
  1816. return svg;
  1817. }
  1818. })();