canvg.js 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921
  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. (function(){
  10. // canvg(target, s)
  11. // empty parameters: replace all 'svg' elements on page with 'canvas' elements
  12. // target: canvas element or the id of a canvas element
  13. // s: svg string, url to svg file, or xml document
  14. // opts: optional hash of options
  15. // ignoreMouse: true => ignore mouse events
  16. // ignoreAnimation: true => ignore animations
  17. // ignoreDimensions: true => does not try to resize canvas
  18. // ignoreClear: true => does not clear canvas
  19. // offsetX: int => draws at a x offset
  20. // offsetY: int => draws at a y offset
  21. // scaleWidth: int => scales horizontally to width
  22. // scaleHeight: int => scales vertically to height
  23. // renderCallback: function => will call the function after the first render is completed
  24. // forceRedraw: function => will call the function on every frame, if it returns true, will redraw
  25. this.canvg = function (target, s, opts) {
  26. // no parameters
  27. if (target == null && s == null && opts == null) {
  28. var svgTags = document.querySelectorAll('svg');
  29. for (var i=0; i<svgTags.length; i++) {
  30. var svgTag = svgTags[i];
  31. var c = document.createElement('canvas');
  32. c.width = svgTag.clientWidth;
  33. c.height = svgTag.clientHeight;
  34. svgTag.parentNode.insertBefore(c, svgTag);
  35. svgTag.parentNode.removeChild(svgTag);
  36. var div = document.createElement('div');
  37. div.appendChild(svgTag);
  38. canvg(c, div.innerHTML);
  39. }
  40. return;
  41. }
  42. if (typeof target == 'string') {
  43. target = document.getElementById(target);
  44. }
  45. // store class on canvas
  46. if (target.svg != null) target.svg.stop();
  47. var svg = build(opts || {});
  48. // on i.e. 8 for flash canvas, we can't assign the property so check for it
  49. if (!(target.childNodes.length == 1 && target.childNodes[0].nodeName == 'OBJECT')) target.svg = svg;
  50. var ctx = target.getContext('2d');
  51. if (typeof(s.documentElement) != 'undefined') {
  52. // load from xml doc
  53. svg.loadXmlDoc(ctx, s);
  54. }
  55. else if (s.substr(0,1) == '<') {
  56. // load from xml string
  57. svg.loadXml(ctx, s);
  58. }
  59. else {
  60. // load from url
  61. svg.load(ctx, s);
  62. }
  63. }
  64. function build(opts) {
  65. var svg = { opts: opts };
  66. svg.FRAMERATE = 30;
  67. svg.MAX_VIRTUAL_PIXELS = 30000;
  68. svg.log = function(msg) {};
  69. if (svg.opts['log'] == true && typeof(console) != 'undefined') {
  70. svg.log = function(msg) { console.log(msg); };
  71. };
  72. // globals
  73. svg.init = function(ctx) {
  74. var uniqueId = 0;
  75. svg.UniqueId = function () { uniqueId++; return 'canvg' + uniqueId; };
  76. svg.Definitions = {};
  77. svg.Styles = {};
  78. svg.Animations = [];
  79. svg.Images = [];
  80. svg.ctx = ctx;
  81. svg.ViewPort = new (function () {
  82. this.viewPorts = [];
  83. this.Clear = function() { this.viewPorts = []; }
  84. this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); }
  85. this.RemoveCurrent = function() { this.viewPorts.pop(); }
  86. this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; }
  87. this.width = function() { return this.Current().width; }
  88. this.height = function() { return this.Current().height; }
  89. this.ComputeSize = function(d) {
  90. if (d != null && typeof(d) == 'number') return d;
  91. if (d == 'x') return this.width();
  92. if (d == 'y') return this.height();
  93. return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2);
  94. }
  95. });
  96. }
  97. svg.init();
  98. // images loaded
  99. svg.ImagesLoaded = function() {
  100. for (var i=0; i<svg.Images.length; i++) {
  101. if (!svg.Images[i].loaded) return false;
  102. }
  103. return true;
  104. }
  105. // trim
  106. svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); }
  107. // compress spaces
  108. svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); }
  109. // ajax
  110. svg.ajax = function(url) {
  111. var AJAX;
  112. if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();}
  113. else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');}
  114. if(AJAX){
  115. AJAX.open('GET',url,false);
  116. AJAX.send(null);
  117. return AJAX.responseText;
  118. }
  119. return null;
  120. }
  121. // parse xml
  122. svg.parseXml = function(xml) {
  123. if (window.DOMParser)
  124. {
  125. var parser = new DOMParser();
  126. return parser.parseFromString(xml, 'text/xml');
  127. }
  128. else
  129. {
  130. xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
  131. var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
  132. xmlDoc.async = 'false';
  133. xmlDoc.loadXML(xml);
  134. return xmlDoc;
  135. }
  136. }
  137. svg.Property = function(name, value) {
  138. this.name = name;
  139. this.value = value;
  140. }
  141. svg.Property.prototype.getValue = function() {
  142. return this.value;
  143. }
  144. svg.Property.prototype.hasValue = function() {
  145. return (this.value != null && this.value !== '');
  146. }
  147. // return the numerical value of the property
  148. svg.Property.prototype.numValue = function() {
  149. if (!this.hasValue()) return 0;
  150. var n = parseFloat(this.value);
  151. if ((this.value + '').match(/%$/)) {
  152. n = n / 100.0;
  153. }
  154. return n;
  155. }
  156. svg.Property.prototype.valueOrDefault = function(def) {
  157. if (this.hasValue()) return this.value;
  158. return def;
  159. }
  160. svg.Property.prototype.numValueOrDefault = function(def) {
  161. if (this.hasValue()) return this.numValue();
  162. return def;
  163. }
  164. // color extensions
  165. // augment the current color value with the opacity
  166. svg.Property.prototype.addOpacity = function(opacityProp) {
  167. var newValue = this.value;
  168. if (opacityProp.value != null && opacityProp.value != '' && typeof(this.value)=='string') { // can only add opacity to colors, not patterns
  169. var color = new RGBColor(this.value);
  170. if (color.ok) {
  171. newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacityProp.numValue() + ')';
  172. }
  173. }
  174. return new svg.Property(this.name, newValue);
  175. }
  176. // definition extensions
  177. // get the definition from the definitions table
  178. svg.Property.prototype.getDefinition = function() {
  179. var name = this.value.match(/#([^\)'"]+)/);
  180. if (name) { name = name[1]; }
  181. if (!name) { name = this.value; }
  182. return svg.Definitions[name];
  183. }
  184. svg.Property.prototype.isUrlDefinition = function() {
  185. return this.value.indexOf('url(') == 0
  186. }
  187. svg.Property.prototype.getFillStyleDefinition = function(e, opacityProp) {
  188. var def = this.getDefinition();
  189. // gradient
  190. if (def != null && def.createGradient) {
  191. return def.createGradient(svg.ctx, e, opacityProp);
  192. }
  193. // pattern
  194. if (def != null && def.createPattern) {
  195. if (def.getHrefAttribute().hasValue()) {
  196. var pt = def.attribute('patternTransform');
  197. def = def.getHrefAttribute().getDefinition();
  198. if (pt.hasValue()) { def.attribute('patternTransform', true).value = pt.value; }
  199. }
  200. return def.createPattern(svg.ctx, e);
  201. }
  202. return null;
  203. }
  204. // length extensions
  205. svg.Property.prototype.getDPI = function(viewPort) {
  206. return 96.0; // TODO: compute?
  207. }
  208. svg.Property.prototype.getEM = function(viewPort) {
  209. var em = 12;
  210. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  211. if (fontSize.hasValue()) em = fontSize.toPixels(viewPort);
  212. return em;
  213. }
  214. svg.Property.prototype.getUnits = function() {
  215. var s = this.value+'';
  216. return s.replace(/[0-9\.\-]/g,'');
  217. }
  218. // get the length as pixels
  219. svg.Property.prototype.toPixels = function(viewPort, processPercent) {
  220. if (!this.hasValue()) return 0;
  221. var s = this.value+'';
  222. if (s.match(/em$/)) return this.numValue() * this.getEM(viewPort);
  223. if (s.match(/ex$/)) return this.numValue() * this.getEM(viewPort) / 2.0;
  224. if (s.match(/px$/)) return this.numValue();
  225. if (s.match(/pt$/)) return this.numValue() * this.getDPI(viewPort) * (1.0 / 72.0);
  226. if (s.match(/pc$/)) return this.numValue() * 15;
  227. if (s.match(/cm$/)) return this.numValue() * this.getDPI(viewPort) / 2.54;
  228. if (s.match(/mm$/)) return this.numValue() * this.getDPI(viewPort) / 25.4;
  229. if (s.match(/in$/)) return this.numValue() * this.getDPI(viewPort);
  230. if (s.match(/%$/)) return this.numValue() * svg.ViewPort.ComputeSize(viewPort);
  231. var n = this.numValue();
  232. if (processPercent && n < 1.0) return n * svg.ViewPort.ComputeSize(viewPort);
  233. return n;
  234. }
  235. // time extensions
  236. // get the time as milliseconds
  237. svg.Property.prototype.toMilliseconds = function() {
  238. if (!this.hasValue()) return 0;
  239. var s = this.value+'';
  240. if (s.match(/s$/)) return this.numValue() * 1000;
  241. if (s.match(/ms$/)) return this.numValue();
  242. return this.numValue();
  243. }
  244. // angle extensions
  245. // get the angle as radians
  246. svg.Property.prototype.toRadians = function() {
  247. if (!this.hasValue()) return 0;
  248. var s = this.value+'';
  249. if (s.match(/deg$/)) return this.numValue() * (Math.PI / 180.0);
  250. if (s.match(/grad$/)) return this.numValue() * (Math.PI / 200.0);
  251. if (s.match(/rad$/)) return this.numValue();
  252. return this.numValue() * (Math.PI / 180.0);
  253. }
  254. // text extensions
  255. // get the text baseline
  256. var textBaselineMapping = {
  257. 'baseline': 'alphabetic',
  258. 'before-edge': 'top',
  259. 'text-before-edge': 'top',
  260. 'middle': 'middle',
  261. 'central': 'middle',
  262. 'after-edge': 'bottom',
  263. 'text-after-edge': 'bottom',
  264. 'ideographic': 'ideographic',
  265. 'alphabetic': 'alphabetic',
  266. 'hanging': 'hanging',
  267. 'mathematical': 'alphabetic'
  268. };
  269. svg.Property.prototype.toTextBaseline = function () {
  270. if (!this.hasValue()) return null;
  271. return textBaselineMapping[this.value];
  272. }
  273. // fonts
  274. svg.Font = new (function() {
  275. this.Styles = 'normal|italic|oblique|inherit';
  276. this.Variants = 'normal|small-caps|inherit';
  277. this.Weights = 'normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit';
  278. this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) {
  279. var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font);
  280. return {
  281. fontFamily: fontFamily || f.fontFamily,
  282. fontSize: fontSize || f.fontSize,
  283. fontStyle: fontStyle || f.fontStyle,
  284. fontWeight: fontWeight || f.fontWeight,
  285. fontVariant: fontVariant || f.fontVariant,
  286. toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') }
  287. }
  288. }
  289. var that = this;
  290. this.Parse = function(s) {
  291. var f = {};
  292. var d = svg.trim(svg.compressSpaces(s || '')).split(' ');
  293. var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false }
  294. var ff = '';
  295. for (var i=0; i<d.length; i++) {
  296. if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; }
  297. else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; }
  298. 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; }
  299. else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; }
  300. else { if (d[i] != 'inherit') ff += d[i]; }
  301. } if (ff != '') f.fontFamily = ff;
  302. return f;
  303. }
  304. });
  305. // points and paths
  306. svg.ToNumberArray = function(s) {
  307. var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' ');
  308. for (var i=0; i<a.length; i++) {
  309. a[i] = parseFloat(a[i]);
  310. }
  311. return a;
  312. }
  313. svg.Point = function(x, y) {
  314. this.x = x;
  315. this.y = y;
  316. }
  317. svg.Point.prototype.angleTo = function(p) {
  318. return Math.atan2(p.y - this.y, p.x - this.x);
  319. }
  320. svg.Point.prototype.applyTransform = function(v) {
  321. var xp = this.x * v[0] + this.y * v[2] + v[4];
  322. var yp = this.x * v[1] + this.y * v[3] + v[5];
  323. this.x = xp;
  324. this.y = yp;
  325. }
  326. svg.CreatePoint = function(s) {
  327. var a = svg.ToNumberArray(s);
  328. return new svg.Point(a[0], a[1]);
  329. }
  330. svg.CreatePath = function(s) {
  331. var a = svg.ToNumberArray(s);
  332. var path = [];
  333. for (var i=0; i<a.length; i+=2) {
  334. path.push(new svg.Point(a[i], a[i+1]));
  335. }
  336. return path;
  337. }
  338. // bounding box
  339. svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want
  340. this.x1 = Number.NaN;
  341. this.y1 = Number.NaN;
  342. this.x2 = Number.NaN;
  343. this.y2 = Number.NaN;
  344. this.x = function() { return this.x1; }
  345. this.y = function() { return this.y1; }
  346. this.width = function() { return this.x2 - this.x1; }
  347. this.height = function() { return this.y2 - this.y1; }
  348. this.addPoint = function(x, y) {
  349. if (x != null) {
  350. if (isNaN(this.x1) || isNaN(this.x2)) {
  351. this.x1 = x;
  352. this.x2 = x;
  353. }
  354. if (x < this.x1) this.x1 = x;
  355. if (x > this.x2) this.x2 = x;
  356. }
  357. if (y != null) {
  358. if (isNaN(this.y1) || isNaN(this.y2)) {
  359. this.y1 = y;
  360. this.y2 = y;
  361. }
  362. if (y < this.y1) this.y1 = y;
  363. if (y > this.y2) this.y2 = y;
  364. }
  365. }
  366. this.addX = function(x) { this.addPoint(x, null); }
  367. this.addY = function(y) { this.addPoint(null, y); }
  368. this.addBoundingBox = function(bb) {
  369. this.addPoint(bb.x1, bb.y1);
  370. this.addPoint(bb.x2, bb.y2);
  371. }
  372. this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) {
  373. var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0)
  374. var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0)
  375. var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0)
  376. var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0)
  377. this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y);
  378. }
  379. this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
  380. // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
  381. var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y];
  382. this.addPoint(p0[0], p0[1]);
  383. this.addPoint(p3[0], p3[1]);
  384. for (i=0; i<=1; i++) {
  385. var f = function(t) {
  386. return Math.pow(1-t, 3) * p0[i]
  387. + 3 * Math.pow(1-t, 2) * t * p1[i]
  388. + 3 * (1-t) * Math.pow(t, 2) * p2[i]
  389. + Math.pow(t, 3) * p3[i];
  390. }
  391. var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
  392. var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
  393. var c = 3 * p1[i] - 3 * p0[i];
  394. if (a == 0) {
  395. if (b == 0) continue;
  396. var t = -c / b;
  397. if (0 < t && t < 1) {
  398. if (i == 0) this.addX(f(t));
  399. if (i == 1) this.addY(f(t));
  400. }
  401. continue;
  402. }
  403. var b2ac = Math.pow(b, 2) - 4 * c * a;
  404. if (b2ac < 0) continue;
  405. var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
  406. if (0 < t1 && t1 < 1) {
  407. if (i == 0) this.addX(f(t1));
  408. if (i == 1) this.addY(f(t1));
  409. }
  410. var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
  411. if (0 < t2 && t2 < 1) {
  412. if (i == 0) this.addX(f(t2));
  413. if (i == 1) this.addY(f(t2));
  414. }
  415. }
  416. }
  417. this.isPointInBox = function(x, y) {
  418. return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2);
  419. }
  420. this.addPoint(x1, y1);
  421. this.addPoint(x2, y2);
  422. }
  423. // transforms
  424. svg.Transform = function(v) {
  425. var that = this;
  426. this.Type = {}
  427. // translate
  428. this.Type.translate = function(s) {
  429. this.p = svg.CreatePoint(s);
  430. this.apply = function(ctx) {
  431. ctx.translate(this.p.x || 0.0, this.p.y || 0.0);
  432. }
  433. this.unapply = function(ctx) {
  434. ctx.translate(-1.0 * this.p.x || 0.0, -1.0 * this.p.y || 0.0);
  435. }
  436. this.applyToPoint = function(p) {
  437. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  438. }
  439. }
  440. // rotate
  441. this.Type.rotate = function(s) {
  442. var a = svg.ToNumberArray(s);
  443. this.angle = new svg.Property('angle', a[0]);
  444. this.cx = a[1] || 0;
  445. this.cy = a[2] || 0;
  446. this.apply = function(ctx) {
  447. ctx.translate(this.cx, this.cy);
  448. ctx.rotate(this.angle.toRadians());
  449. ctx.translate(-this.cx, -this.cy);
  450. }
  451. this.unapply = function(ctx) {
  452. ctx.translate(this.cx, this.cy);
  453. ctx.rotate(-1.0 * this.angle.toRadians());
  454. ctx.translate(-this.cx, -this.cy);
  455. }
  456. this.applyToPoint = function(p) {
  457. var a = this.angle.toRadians();
  458. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  459. p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]);
  460. p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]);
  461. }
  462. }
  463. this.Type.scale = function(s) {
  464. this.p = svg.CreatePoint(s);
  465. this.apply = function(ctx) {
  466. ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0);
  467. }
  468. this.unapply = function(ctx) {
  469. ctx.scale(1.0 / this.p.x || 1.0, 1.0 / this.p.y || this.p.x || 1.0);
  470. }
  471. this.applyToPoint = function(p) {
  472. p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]);
  473. }
  474. }
  475. this.Type.matrix = function(s) {
  476. this.m = svg.ToNumberArray(s);
  477. this.apply = function(ctx) {
  478. ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
  479. }
  480. this.applyToPoint = function(p) {
  481. p.applyTransform(this.m);
  482. }
  483. }
  484. this.Type.SkewBase = function(s) {
  485. this.base = that.Type.matrix;
  486. this.base(s);
  487. this.angle = new svg.Property('angle', s);
  488. }
  489. this.Type.SkewBase.prototype = new this.Type.matrix;
  490. this.Type.skewX = function(s) {
  491. this.base = that.Type.SkewBase;
  492. this.base(s);
  493. this.m = [1, 0, Math.tan(this.angle.toRadians()), 1, 0, 0];
  494. }
  495. this.Type.skewX.prototype = new this.Type.SkewBase;
  496. this.Type.skewY = function(s) {
  497. this.base = that.Type.SkewBase;
  498. this.base(s);
  499. this.m = [1, Math.tan(this.angle.toRadians()), 0, 1, 0, 0];
  500. }
  501. this.Type.skewY.prototype = new this.Type.SkewBase;
  502. this.transforms = [];
  503. this.apply = function(ctx) {
  504. for (var i=0; i<this.transforms.length; i++) {
  505. this.transforms[i].apply(ctx);
  506. }
  507. }
  508. this.unapply = function(ctx) {
  509. for (var i=this.transforms.length-1; i>=0; i--) {
  510. this.transforms[i].unapply(ctx);
  511. }
  512. }
  513. this.applyToPoint = function(p) {
  514. for (var i=0; i<this.transforms.length; i++) {
  515. this.transforms[i].applyToPoint(p);
  516. }
  517. }
  518. var data = svg.trim(svg.compressSpaces(v)).replace(/\)([a-zA-Z])/g, ') $1').replace(/\)(\s?,\s?)/g,') ').split(/\s(?=[a-z])/);
  519. for (var i=0; i<data.length; i++) {
  520. var type = svg.trim(data[i].split('(')[0]);
  521. var s = data[i].split('(')[1].replace(')','');
  522. var transform = new this.Type[type](s);
  523. transform.type = type;
  524. this.transforms.push(transform);
  525. }
  526. }
  527. // aspect ratio
  528. svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {
  529. // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
  530. aspectRatio = svg.compressSpaces(aspectRatio);
  531. aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer
  532. var align = aspectRatio.split(' ')[0] || 'xMidYMid';
  533. var meetOrSlice = aspectRatio.split(' ')[1] || 'meet';
  534. // calculate scale
  535. var scaleX = width / desiredWidth;
  536. var scaleY = height / desiredHeight;
  537. var scaleMin = Math.min(scaleX, scaleY);
  538. var scaleMax = Math.max(scaleX, scaleY);
  539. if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; }
  540. if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; }
  541. refX = new svg.Property('refX', refX);
  542. refY = new svg.Property('refY', refY);
  543. if (refX.hasValue() && refY.hasValue()) {
  544. ctx.translate(-scaleMin * refX.toPixels('x'), -scaleMin * refY.toPixels('y'));
  545. }
  546. else {
  547. // align
  548. if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);
  549. if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);
  550. if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0);
  551. if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight);
  552. }
  553. // scale
  554. if (align == 'none') ctx.scale(scaleX, scaleY);
  555. else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin);
  556. else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax);
  557. // translate
  558. ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);
  559. }
  560. // elements
  561. svg.Element = {}
  562. svg.EmptyProperty = new svg.Property('EMPTY', '');
  563. svg.Element.ElementBase = function(node) {
  564. this.attributes = {};
  565. this.styles = {};
  566. this.children = [];
  567. // get or create attribute
  568. this.attribute = function(name, createIfNotExists) {
  569. var a = this.attributes[name];
  570. if (a != null) return a;
  571. if (createIfNotExists == true) { a = new svg.Property(name, ''); this.attributes[name] = a; }
  572. return a || svg.EmptyProperty;
  573. }
  574. this.getHrefAttribute = function() {
  575. for (var a in this.attributes) {
  576. if (a.match(/:href$/)) {
  577. return this.attributes[a];
  578. }
  579. }
  580. return svg.EmptyProperty;
  581. }
  582. // get or create style, crawls up node tree
  583. this.style = function(name, createIfNotExists, skipAncestors) {
  584. var s = this.styles[name];
  585. if (s != null) return s;
  586. var a = this.attribute(name);
  587. if (a != null && a.hasValue()) {
  588. this.styles[name] = a; // move up to me to cache
  589. return a;
  590. }
  591. if (skipAncestors != true) {
  592. var p = this.parent;
  593. if (p != null) {
  594. var ps = p.style(name);
  595. if (ps != null && ps.hasValue()) {
  596. return ps;
  597. }
  598. }
  599. }
  600. if (createIfNotExists == true) { s = new svg.Property(name, ''); this.styles[name] = s; }
  601. return s || svg.EmptyProperty;
  602. }
  603. // base render
  604. this.render = function(ctx) {
  605. // don't render display=none
  606. if (this.style('display').value == 'none') return;
  607. // don't render visibility=hidden
  608. if (this.style('visibility').value == 'hidden') return;
  609. ctx.save();
  610. if (this.attribute('mask').hasValue()) { // mask
  611. var mask = this.attribute('mask').getDefinition();
  612. if (mask != null) mask.apply(ctx, this);
  613. }
  614. else if (this.style('filter').hasValue()) { // filter
  615. var filter = this.style('filter').getDefinition();
  616. if (filter != null) filter.apply(ctx, this);
  617. }
  618. else {
  619. this.setContext(ctx);
  620. this.renderChildren(ctx);
  621. this.clearContext(ctx);
  622. }
  623. ctx.restore();
  624. }
  625. // base set context
  626. this.setContext = function(ctx) {
  627. // OVERRIDE ME!
  628. }
  629. // base clear context
  630. this.clearContext = function(ctx) {
  631. // OVERRIDE ME!
  632. }
  633. // base render children
  634. this.renderChildren = function(ctx) {
  635. for (var i=0; i<this.children.length; i++) {
  636. this.children[i].render(ctx);
  637. }
  638. }
  639. this.addChild = function(childNode, create) {
  640. var child = childNode;
  641. if (create) child = svg.CreateElement(childNode);
  642. child.parent = this;
  643. if (child.type != 'title') { this.children.push(child); }
  644. }
  645. if (node != null && node.nodeType == 1) { //ELEMENT_NODE
  646. // add children
  647. for (var i=0; i<node.childNodes.length; i++) {
  648. var childNode = node.childNodes[i];
  649. if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE
  650. if (this.captureTextNodes && (childNode.nodeType == 3 || childNode.nodeType == 4)) {
  651. var text = childNode.nodeValue || childNode.text || '';
  652. if (svg.trim(svg.compressSpaces(text)) != '') {
  653. this.addChild(new svg.Element.tspan(childNode), false); // TEXT_NODE
  654. }
  655. }
  656. }
  657. // add attributes
  658. for (var i=0; i<node.attributes.length; i++) {
  659. var attribute = node.attributes[i];
  660. this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue);
  661. }
  662. // add tag styles
  663. var styles = svg.Styles[node.nodeName];
  664. if (styles != null) {
  665. for (var name in styles) {
  666. this.styles[name] = styles[name];
  667. }
  668. }
  669. // add class styles
  670. if (this.attribute('class').hasValue()) {
  671. var classes = svg.compressSpaces(this.attribute('class').value).split(' ');
  672. for (var j=0; j<classes.length; j++) {
  673. styles = svg.Styles['.'+classes[j]];
  674. if (styles != null) {
  675. for (var name in styles) {
  676. this.styles[name] = styles[name];
  677. }
  678. }
  679. styles = svg.Styles[node.nodeName+'.'+classes[j]];
  680. if (styles != null) {
  681. for (var name in styles) {
  682. this.styles[name] = styles[name];
  683. }
  684. }
  685. }
  686. }
  687. // add id styles
  688. if (this.attribute('id').hasValue()) {
  689. var styles = svg.Styles['#' + this.attribute('id').value];
  690. if (styles != null) {
  691. for (var name in styles) {
  692. this.styles[name] = styles[name];
  693. }
  694. }
  695. }
  696. // add inline styles
  697. if (this.attribute('style').hasValue()) {
  698. var styles = this.attribute('style').value.split(';');
  699. for (var i=0; i<styles.length; i++) {
  700. if (svg.trim(styles[i]) != '') {
  701. var style = styles[i].split(':');
  702. var name = svg.trim(style[0]);
  703. var value = svg.trim(style[1]);
  704. this.styles[name] = new svg.Property(name, value);
  705. }
  706. }
  707. }
  708. // add id
  709. if (this.attribute('id').hasValue()) {
  710. if (svg.Definitions[this.attribute('id').value] == null) {
  711. svg.Definitions[this.attribute('id').value] = this;
  712. }
  713. }
  714. }
  715. }
  716. svg.Element.RenderedElementBase = function(node) {
  717. this.base = svg.Element.ElementBase;
  718. this.base(node);
  719. this.setContext = function(ctx) {
  720. // fill
  721. if (this.style('fill').isUrlDefinition()) {
  722. var fs = this.style('fill').getFillStyleDefinition(this, this.style('fill-opacity'));
  723. if (fs != null) ctx.fillStyle = fs;
  724. }
  725. else if (this.style('fill').hasValue()) {
  726. var fillStyle = this.style('fill');
  727. if (fillStyle.value == 'currentColor') fillStyle.value = this.style('color').value;
  728. ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);
  729. }
  730. if (this.style('fill-opacity').hasValue()) {
  731. var fillStyle = new svg.Property('fill', ctx.fillStyle);
  732. fillStyle = fillStyle.addOpacity(this.style('fill-opacity'));
  733. ctx.fillStyle = fillStyle.value;
  734. }
  735. // stroke
  736. if (this.style('stroke').isUrlDefinition()) {
  737. var fs = this.style('stroke').getFillStyleDefinition(this, this.style('stroke-opacity'));
  738. if (fs != null) ctx.strokeStyle = fs;
  739. }
  740. else if (this.style('stroke').hasValue()) {
  741. var strokeStyle = this.style('stroke');
  742. if (strokeStyle.value == 'currentColor') strokeStyle.value = this.style('color').value;
  743. ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);
  744. }
  745. if (this.style('stroke-opacity').hasValue()) {
  746. var strokeStyle = new svg.Property('stroke', ctx.strokeStyle);
  747. strokeStyle = strokeStyle.addOpacity(this.style('stroke-opacity'));
  748. ctx.strokeStyle = strokeStyle.value;
  749. }
  750. if (this.style('stroke-width').hasValue()) {
  751. var newLineWidth = this.style('stroke-width').toPixels();
  752. ctx.lineWidth = newLineWidth == 0 ? 0.001 : newLineWidth; // browsers don't respect 0
  753. }
  754. if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;
  755. if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;
  756. if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;
  757. if (this.style('stroke-dasharray').hasValue() && this.style('stroke-dasharray').value != 'none') {
  758. var gaps = svg.ToNumberArray(this.style('stroke-dasharray').value);
  759. if (typeof(ctx.setLineDash) != 'undefined') { ctx.setLineDash(gaps); }
  760. else if (typeof(ctx.webkitLineDash) != 'undefined') { ctx.webkitLineDash = gaps; }
  761. else if (typeof(ctx.mozDash) != 'undefined' && !(gaps.length==1 && gaps[0]==0)) { ctx.mozDash = gaps; }
  762. var offset = this.style('stroke-dashoffset').numValueOrDefault(1);
  763. if (typeof(ctx.lineDashOffset) != 'undefined') { ctx.lineDashOffset = offset; }
  764. else if (typeof(ctx.webkitLineDashOffset) != 'undefined') { ctx.webkitLineDashOffset = offset; }
  765. else if (typeof(ctx.mozDashOffset) != 'undefined') { ctx.mozDashOffset = offset; }
  766. }
  767. // font
  768. if (typeof(ctx.font) != 'undefined') {
  769. ctx.font = svg.Font.CreateFont(
  770. this.style('font-style').value,
  771. this.style('font-variant').value,
  772. this.style('font-weight').value,
  773. this.style('font-size').hasValue() ? this.style('font-size').toPixels() + 'px' : '',
  774. this.style('font-family').value).toString();
  775. }
  776. // transform
  777. if (this.attribute('transform').hasValue()) {
  778. var transform = new svg.Transform(this.attribute('transform').value);
  779. transform.apply(ctx);
  780. }
  781. // clip
  782. if (this.style('clip-path', false, true).hasValue()) {
  783. var clip = this.style('clip-path', false, true).getDefinition();
  784. if (clip != null) clip.apply(ctx);
  785. }
  786. // opacity
  787. if (this.style('opacity').hasValue()) {
  788. ctx.globalAlpha = this.style('opacity').numValue();
  789. }
  790. }
  791. }
  792. svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase;
  793. svg.Element.PathElementBase = function(node) {
  794. this.base = svg.Element.RenderedElementBase;
  795. this.base(node);
  796. this.path = function(ctx) {
  797. if (ctx != null) ctx.beginPath();
  798. return new svg.BoundingBox();
  799. }
  800. this.renderChildren = function(ctx) {
  801. this.path(ctx);
  802. svg.Mouse.checkPath(this, ctx);
  803. if (ctx.fillStyle != '') {
  804. if (this.style('fill-rule').valueOrDefault('inherit') != 'inherit') { ctx.fill(this.style('fill-rule').value); }
  805. else { ctx.fill(); }
  806. }
  807. if (ctx.strokeStyle != '') ctx.stroke();
  808. var markers = this.getMarkers();
  809. if (markers != null) {
  810. if (this.style('marker-start').isUrlDefinition()) {
  811. var marker = this.style('marker-start').getDefinition();
  812. marker.render(ctx, markers[0][0], markers[0][1]);
  813. }
  814. if (this.style('marker-mid').isUrlDefinition()) {
  815. var marker = this.style('marker-mid').getDefinition();
  816. for (var i=1;i<markers.length-1;i++) {
  817. marker.render(ctx, markers[i][0], markers[i][1]);
  818. }
  819. }
  820. if (this.style('marker-end').isUrlDefinition()) {
  821. var marker = this.style('marker-end').getDefinition();
  822. marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]);
  823. }
  824. }
  825. }
  826. this.getBoundingBox = function() {
  827. return this.path();
  828. }
  829. this.getMarkers = function() {
  830. return null;
  831. }
  832. }
  833. svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase;
  834. // svg element
  835. svg.Element.svg = function(node) {
  836. this.base = svg.Element.RenderedElementBase;
  837. this.base(node);
  838. this.baseClearContext = this.clearContext;
  839. this.clearContext = function(ctx) {
  840. this.baseClearContext(ctx);
  841. svg.ViewPort.RemoveCurrent();
  842. }
  843. this.baseSetContext = this.setContext;
  844. this.setContext = function(ctx) {
  845. // initial values and defaults
  846. ctx.strokeStyle = 'rgba(0,0,0,0)';
  847. ctx.lineCap = 'butt';
  848. ctx.lineJoin = 'miter';
  849. ctx.miterLimit = 4;
  850. if (typeof(ctx.font) != 'undefined' && typeof(window.getComputedStyle) != 'undefined') {
  851. ctx.font = window.getComputedStyle(ctx.canvas).getPropertyValue('font');
  852. }
  853. this.baseSetContext(ctx);
  854. // create new view port
  855. if (!this.attribute('x').hasValue()) this.attribute('x', true).value = 0;
  856. if (!this.attribute('y').hasValue()) this.attribute('y', true).value = 0;
  857. ctx.translate(this.attribute('x').toPixels('x'), this.attribute('y').toPixels('y'));
  858. var width = svg.ViewPort.width();
  859. var height = svg.ViewPort.height();
  860. if (!this.attribute('width').hasValue()) this.attribute('width', true).value = '100%';
  861. if (!this.attribute('height').hasValue()) this.attribute('height', true).value = '100%';
  862. if (typeof(this.root) == 'undefined') {
  863. width = this.attribute('width').toPixels('x');
  864. height = this.attribute('height').toPixels('y');
  865. var x = 0;
  866. var y = 0;
  867. if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {
  868. x = -this.attribute('refX').toPixels('x');
  869. y = -this.attribute('refY').toPixels('y');
  870. }
  871. if (this.attribute('overflow').valueOrDefault('hidden') != 'visible') {
  872. ctx.beginPath();
  873. ctx.moveTo(x, y);
  874. ctx.lineTo(width, y);
  875. ctx.lineTo(width, height);
  876. ctx.lineTo(x, height);
  877. ctx.closePath();
  878. ctx.clip();
  879. }
  880. }
  881. svg.ViewPort.SetCurrent(width, height);
  882. // viewbox
  883. if (this.attribute('viewBox').hasValue()) {
  884. var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
  885. var minX = viewBox[0];
  886. var minY = viewBox[1];
  887. width = viewBox[2];
  888. height = viewBox[3];
  889. svg.AspectRatio(ctx,
  890. this.attribute('preserveAspectRatio').value,
  891. svg.ViewPort.width(),
  892. width,
  893. svg.ViewPort.height(),
  894. height,
  895. minX,
  896. minY,
  897. this.attribute('refX').value,
  898. this.attribute('refY').value);
  899. svg.ViewPort.RemoveCurrent();
  900. svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
  901. }
  902. }
  903. }
  904. svg.Element.svg.prototype = new svg.Element.RenderedElementBase;
  905. // rect element
  906. svg.Element.rect = function(node) {
  907. this.base = svg.Element.PathElementBase;
  908. this.base(node);
  909. this.path = function(ctx) {
  910. var x = this.attribute('x').toPixels('x');
  911. var y = this.attribute('y').toPixels('y');
  912. var width = this.attribute('width').toPixels('x');
  913. var height = this.attribute('height').toPixels('y');
  914. var rx = this.attribute('rx').toPixels('x');
  915. var ry = this.attribute('ry').toPixels('y');
  916. if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;
  917. if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;
  918. rx = Math.min(rx, width / 2.0);
  919. ry = Math.min(ry, height / 2.0);
  920. if (ctx != null) {
  921. ctx.beginPath();
  922. ctx.moveTo(x + rx, y);
  923. ctx.lineTo(x + width - rx, y);
  924. ctx.quadraticCurveTo(x + width, y, x + width, y + ry)
  925. ctx.lineTo(x + width, y + height - ry);
  926. ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height)
  927. ctx.lineTo(x + rx, y + height);
  928. ctx.quadraticCurveTo(x, y + height, x, y + height - ry)
  929. ctx.lineTo(x, y + ry);
  930. ctx.quadraticCurveTo(x, y, x + rx, y)
  931. ctx.closePath();
  932. }
  933. return new svg.BoundingBox(x, y, x + width, y + height);
  934. }
  935. }
  936. svg.Element.rect.prototype = new svg.Element.PathElementBase;
  937. // circle element
  938. svg.Element.circle = function(node) {
  939. this.base = svg.Element.PathElementBase;
  940. this.base(node);
  941. this.path = function(ctx) {
  942. var cx = this.attribute('cx').toPixels('x');
  943. var cy = this.attribute('cy').toPixels('y');
  944. var r = this.attribute('r').toPixels();
  945. if (ctx != null) {
  946. ctx.beginPath();
  947. ctx.arc(cx, cy, r, 0, Math.PI * 2, true);
  948. ctx.closePath();
  949. }
  950. return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);
  951. }
  952. }
  953. svg.Element.circle.prototype = new svg.Element.PathElementBase;
  954. // ellipse element
  955. svg.Element.ellipse = function(node) {
  956. this.base = svg.Element.PathElementBase;
  957. this.base(node);
  958. this.path = function(ctx) {
  959. var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
  960. var rx = this.attribute('rx').toPixels('x');
  961. var ry = this.attribute('ry').toPixels('y');
  962. var cx = this.attribute('cx').toPixels('x');
  963. var cy = this.attribute('cy').toPixels('y');
  964. if (ctx != null) {
  965. ctx.beginPath();
  966. ctx.moveTo(cx, cy - ry);
  967. ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);
  968. ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);
  969. ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);
  970. ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);
  971. ctx.closePath();
  972. }
  973. return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);
  974. }
  975. }
  976. svg.Element.ellipse.prototype = new svg.Element.PathElementBase;
  977. // line element
  978. svg.Element.line = function(node) {
  979. this.base = svg.Element.PathElementBase;
  980. this.base(node);
  981. this.getPoints = function() {
  982. return [
  983. new svg.Point(this.attribute('x1').toPixels('x'), this.attribute('y1').toPixels('y')),
  984. new svg.Point(this.attribute('x2').toPixels('x'), this.attribute('y2').toPixels('y'))];
  985. }
  986. this.path = function(ctx) {
  987. var points = this.getPoints();
  988. if (ctx != null) {
  989. ctx.beginPath();
  990. ctx.moveTo(points[0].x, points[0].y);
  991. ctx.lineTo(points[1].x, points[1].y);
  992. }
  993. return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);
  994. }
  995. this.getMarkers = function() {
  996. var points = this.getPoints();
  997. var a = points[0].angleTo(points[1]);
  998. return [[points[0], a], [points[1], a]];
  999. }
  1000. }
  1001. svg.Element.line.prototype = new svg.Element.PathElementBase;
  1002. // polyline element
  1003. svg.Element.polyline = function(node) {
  1004. this.base = svg.Element.PathElementBase;
  1005. this.base(node);
  1006. this.points = svg.CreatePath(this.attribute('points').value);
  1007. this.path = function(ctx) {
  1008. var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);
  1009. if (ctx != null) {
  1010. ctx.beginPath();
  1011. ctx.moveTo(this.points[0].x, this.points[0].y);
  1012. }
  1013. for (var i=1; i<this.points.length; i++) {
  1014. bb.addPoint(this.points[i].x, this.points[i].y);
  1015. if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);
  1016. }
  1017. return bb;
  1018. }
  1019. this.getMarkers = function() {
  1020. var markers = [];
  1021. for (var i=0; i<this.points.length - 1; i++) {
  1022. markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]);
  1023. }
  1024. markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]);
  1025. return markers;
  1026. }
  1027. }
  1028. svg.Element.polyline.prototype = new svg.Element.PathElementBase;
  1029. // polygon element
  1030. svg.Element.polygon = function(node) {
  1031. this.base = svg.Element.polyline;
  1032. this.base(node);
  1033. this.basePath = this.path;
  1034. this.path = function(ctx) {
  1035. var bb = this.basePath(ctx);
  1036. if (ctx != null) {
  1037. ctx.lineTo(this.points[0].x, this.points[0].y);
  1038. ctx.closePath();
  1039. }
  1040. return bb;
  1041. }
  1042. }
  1043. svg.Element.polygon.prototype = new svg.Element.polyline;
  1044. // path element
  1045. svg.Element.path = function(node) {
  1046. this.base = svg.Element.PathElementBase;
  1047. this.base(node);
  1048. var d = this.attribute('d').value;
  1049. // TODO: convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF
  1050. d = d.replace(/,/gm,' '); // get rid of all commas
  1051. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
  1052. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
  1053. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // separate commands from points
  1054. d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from points
  1055. d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma
  1056. d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma
  1057. d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax
  1058. d = svg.compressSpaces(d); // compress multiple spaces
  1059. d = svg.trim(d);
  1060. this.PathParser = new (function(d) {
  1061. this.tokens = d.split(' ');
  1062. this.reset = function() {
  1063. this.i = -1;
  1064. this.command = '';
  1065. this.previousCommand = '';
  1066. this.start = new svg.Point(0, 0);
  1067. this.control = new svg.Point(0, 0);
  1068. this.current = new svg.Point(0, 0);
  1069. this.points = [];
  1070. this.angles = [];
  1071. }
  1072. this.isEnd = function() {
  1073. return this.i >= this.tokens.length - 1;
  1074. }
  1075. this.isCommandOrEnd = function() {
  1076. if (this.isEnd()) return true;
  1077. return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null;
  1078. }
  1079. this.isRelativeCommand = function() {
  1080. switch(this.command)
  1081. {
  1082. case 'm':
  1083. case 'l':
  1084. case 'h':
  1085. case 'v':
  1086. case 'c':
  1087. case 's':
  1088. case 'q':
  1089. case 't':
  1090. case 'a':
  1091. case 'z':
  1092. return true;
  1093. break;
  1094. }
  1095. return false;
  1096. }
  1097. this.getToken = function() {
  1098. this.i++;
  1099. return this.tokens[this.i];
  1100. }
  1101. this.getScalar = function() {
  1102. return parseFloat(this.getToken());
  1103. }
  1104. this.nextCommand = function() {
  1105. this.previousCommand = this.command;
  1106. this.command = this.getToken();
  1107. }
  1108. this.getPoint = function() {
  1109. var p = new svg.Point(this.getScalar(), this.getScalar());
  1110. return this.makeAbsolute(p);
  1111. }
  1112. this.getAsControlPoint = function() {
  1113. var p = this.getPoint();
  1114. this.control = p;
  1115. return p;
  1116. }
  1117. this.getAsCurrentPoint = function() {
  1118. var p = this.getPoint();
  1119. this.current = p;
  1120. return p;
  1121. }
  1122. this.getReflectedControlPoint = function() {
  1123. if (this.previousCommand.toLowerCase() != 'c' &&
  1124. this.previousCommand.toLowerCase() != 's' &&
  1125. this.previousCommand.toLowerCase() != 'q' &&
  1126. this.previousCommand.toLowerCase() != 't' ){
  1127. return this.current;
  1128. }
  1129. // reflect point
  1130. var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);
  1131. return p;
  1132. }
  1133. this.makeAbsolute = function(p) {
  1134. if (this.isRelativeCommand()) {
  1135. p.x += this.current.x;
  1136. p.y += this.current.y;
  1137. }
  1138. return p;
  1139. }
  1140. this.addMarker = function(p, from, priorTo) {
  1141. // if the last angle isn't filled in because we didn't have this point yet ...
  1142. if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length-1] == null) {
  1143. this.angles[this.angles.length-1] = this.points[this.points.length-1].angleTo(priorTo);
  1144. }
  1145. this.addMarkerAngle(p, from == null ? null : from.angleTo(p));
  1146. }
  1147. this.addMarkerAngle = function(p, a) {
  1148. this.points.push(p);
  1149. this.angles.push(a);
  1150. }
  1151. this.getMarkerPoints = function() { return this.points; }
  1152. this.getMarkerAngles = function() {
  1153. for (var i=0; i<this.angles.length; i++) {
  1154. if (this.angles[i] == null) {
  1155. for (var j=i+1; j<this.angles.length; j++) {
  1156. if (this.angles[j] != null) {
  1157. this.angles[i] = this.angles[j];
  1158. break;
  1159. }
  1160. }
  1161. }
  1162. }
  1163. return this.angles;
  1164. }
  1165. })(d);
  1166. this.path = function(ctx) {
  1167. var pp = this.PathParser;
  1168. pp.reset();
  1169. var bb = new svg.BoundingBox();
  1170. if (ctx != null) ctx.beginPath();
  1171. while (!pp.isEnd()) {
  1172. pp.nextCommand();
  1173. switch (pp.command) {
  1174. case 'M':
  1175. case 'm':
  1176. var p = pp.getAsCurrentPoint();
  1177. pp.addMarker(p);
  1178. bb.addPoint(p.x, p.y);
  1179. if (ctx != null) ctx.moveTo(p.x, p.y);
  1180. pp.start = pp.current;
  1181. while (!pp.isCommandOrEnd()) {
  1182. var p = pp.getAsCurrentPoint();
  1183. pp.addMarker(p, pp.start);
  1184. bb.addPoint(p.x, p.y);
  1185. if (ctx != null) ctx.lineTo(p.x, p.y);
  1186. }
  1187. break;
  1188. case 'L':
  1189. case 'l':
  1190. while (!pp.isCommandOrEnd()) {
  1191. var c = pp.current;
  1192. var p = pp.getAsCurrentPoint();
  1193. pp.addMarker(p, c);
  1194. bb.addPoint(p.x, p.y);
  1195. if (ctx != null) ctx.lineTo(p.x, p.y);
  1196. }
  1197. break;
  1198. case 'H':
  1199. case 'h':
  1200. while (!pp.isCommandOrEnd()) {
  1201. var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);
  1202. pp.addMarker(newP, pp.current);
  1203. pp.current = newP;
  1204. bb.addPoint(pp.current.x, pp.current.y);
  1205. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1206. }
  1207. break;
  1208. case 'V':
  1209. case 'v':
  1210. while (!pp.isCommandOrEnd()) {
  1211. var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
  1212. pp.addMarker(newP, pp.current);
  1213. pp.current = newP;
  1214. bb.addPoint(pp.current.x, pp.current.y);
  1215. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1216. }
  1217. break;
  1218. case 'C':
  1219. case 'c':
  1220. while (!pp.isCommandOrEnd()) {
  1221. var curr = pp.current;
  1222. var p1 = pp.getPoint();
  1223. var cntrl = pp.getAsControlPoint();
  1224. var cp = pp.getAsCurrentPoint();
  1225. pp.addMarker(cp, cntrl, p1);
  1226. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1227. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1228. }
  1229. break;
  1230. case 'S':
  1231. case 's':
  1232. while (!pp.isCommandOrEnd()) {
  1233. var curr = pp.current;
  1234. var p1 = pp.getReflectedControlPoint();
  1235. var cntrl = pp.getAsControlPoint();
  1236. var cp = pp.getAsCurrentPoint();
  1237. pp.addMarker(cp, cntrl, p1);
  1238. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1239. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1240. }
  1241. break;
  1242. case 'Q':
  1243. case 'q':
  1244. while (!pp.isCommandOrEnd()) {
  1245. var curr = pp.current;
  1246. var cntrl = pp.getAsControlPoint();
  1247. var cp = pp.getAsCurrentPoint();
  1248. pp.addMarker(cp, cntrl, cntrl);
  1249. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1250. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1251. }
  1252. break;
  1253. case 'T':
  1254. case 't':
  1255. while (!pp.isCommandOrEnd()) {
  1256. var curr = pp.current;
  1257. var cntrl = pp.getReflectedControlPoint();
  1258. pp.control = cntrl;
  1259. var cp = pp.getAsCurrentPoint();
  1260. pp.addMarker(cp, cntrl, cntrl);
  1261. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1262. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1263. }
  1264. break;
  1265. case 'A':
  1266. case 'a':
  1267. while (!pp.isCommandOrEnd()) {
  1268. var curr = pp.current;
  1269. var rx = pp.getScalar();
  1270. var ry = pp.getScalar();
  1271. var xAxisRotation = pp.getScalar() * (Math.PI / 180.0);
  1272. var largeArcFlag = pp.getScalar();
  1273. var sweepFlag = pp.getScalar();
  1274. var cp = pp.getAsCurrentPoint();
  1275. // Conversion from endpoint to center parameterization
  1276. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  1277. // x1', y1'
  1278. var currp = new svg.Point(
  1279. Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,
  1280. -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
  1281. );
  1282. // adjust radii
  1283. var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2);
  1284. if (l > 1) {
  1285. rx *= Math.sqrt(l);
  1286. ry *= Math.sqrt(l);
  1287. }
  1288. // cx', cy'
  1289. var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
  1290. ((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))) /
  1291. (Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2))
  1292. );
  1293. if (isNaN(s)) s = 0;
  1294. var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
  1295. // cx, cy
  1296. var centp = new svg.Point(
  1297. (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
  1298. (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
  1299. );
  1300. // vector magnitude
  1301. var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); }
  1302. // ratio between two vectors
  1303. var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) }
  1304. // angle between two vectors
  1305. var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); }
  1306. // initial angle
  1307. var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]);
  1308. // angle delta
  1309. var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry];
  1310. var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry];
  1311. var ad = a(u, v);
  1312. if (r(u,v) <= -1) ad = Math.PI;
  1313. if (r(u,v) >= 1) ad = 0;
  1314. // for markers
  1315. var dir = 1 - sweepFlag ? 1.0 : -1.0;
  1316. var ah = a1 + dir * (ad / 2.0);
  1317. var halfWay = new svg.Point(
  1318. centp.x + rx * Math.cos(ah),
  1319. centp.y + ry * Math.sin(ah)
  1320. );
  1321. pp.addMarkerAngle(halfWay, ah - dir * Math.PI / 2);
  1322. pp.addMarkerAngle(cp, ah - dir * Math.PI);
  1323. bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better
  1324. if (ctx != null) {
  1325. var r = rx > ry ? rx : ry;
  1326. var sx = rx > ry ? 1 : rx / ry;
  1327. var sy = rx > ry ? ry / rx : 1;
  1328. ctx.translate(centp.x, centp.y);
  1329. ctx.rotate(xAxisRotation);
  1330. ctx.scale(sx, sy);
  1331. ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);
  1332. ctx.scale(1/sx, 1/sy);
  1333. ctx.rotate(-xAxisRotation);
  1334. ctx.translate(-centp.x, -centp.y);
  1335. }
  1336. }
  1337. break;
  1338. case 'Z':
  1339. case 'z':
  1340. if (ctx != null) ctx.closePath();
  1341. pp.current = pp.start;
  1342. }
  1343. }
  1344. return bb;
  1345. }
  1346. this.getMarkers = function() {
  1347. var points = this.PathParser.getMarkerPoints();
  1348. var angles = this.PathParser.getMarkerAngles();
  1349. var markers = [];
  1350. for (var i=0; i<points.length; i++) {
  1351. markers.push([points[i], angles[i]]);
  1352. }
  1353. return markers;
  1354. }
  1355. }
  1356. svg.Element.path.prototype = new svg.Element.PathElementBase;
  1357. // pattern element
  1358. svg.Element.pattern = function(node) {
  1359. this.base = svg.Element.ElementBase;
  1360. this.base(node);
  1361. this.createPattern = function(ctx, element) {
  1362. var width = this.attribute('width').toPixels('x', true);
  1363. var height = this.attribute('height').toPixels('y', true);
  1364. // render me using a temporary svg element
  1365. var tempSvg = new svg.Element.svg();
  1366. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1367. tempSvg.attributes['width'] = new svg.Property('width', width + 'px');
  1368. tempSvg.attributes['height'] = new svg.Property('height', height + 'px');
  1369. tempSvg.attributes['transform'] = new svg.Property('transform', this.attribute('patternTransform').value);
  1370. tempSvg.children = this.children;
  1371. var c = document.createElement('canvas');
  1372. c.width = width;
  1373. c.height = height;
  1374. var cctx = c.getContext('2d');
  1375. if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {
  1376. cctx.translate(this.attribute('x').toPixels('x', true), this.attribute('y').toPixels('y', true));
  1377. }
  1378. // render 3x3 grid so when we transform there's no white space on edges
  1379. for (var x=-1; x<=1; x++) {
  1380. for (var y=-1; y<=1; y++) {
  1381. cctx.save();
  1382. cctx.translate(x * c.width, y * c.height);
  1383. tempSvg.render(cctx);
  1384. cctx.restore();
  1385. }
  1386. }
  1387. var pattern = ctx.createPattern(c, 'repeat');
  1388. return pattern;
  1389. }
  1390. }
  1391. svg.Element.pattern.prototype = new svg.Element.ElementBase;
  1392. // marker element
  1393. svg.Element.marker = function(node) {
  1394. this.base = svg.Element.ElementBase;
  1395. this.base(node);
  1396. this.baseRender = this.render;
  1397. this.render = function(ctx, point, angle) {
  1398. ctx.translate(point.x, point.y);
  1399. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle);
  1400. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);
  1401. ctx.save();
  1402. // render me using a temporary svg element
  1403. var tempSvg = new svg.Element.svg();
  1404. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1405. tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);
  1406. tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);
  1407. tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);
  1408. tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);
  1409. tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));
  1410. tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));
  1411. tempSvg.children = this.children;
  1412. tempSvg.render(ctx);
  1413. ctx.restore();
  1414. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth);
  1415. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle);
  1416. ctx.translate(-point.x, -point.y);
  1417. }
  1418. }
  1419. svg.Element.marker.prototype = new svg.Element.ElementBase;
  1420. // definitions element
  1421. svg.Element.defs = function(node) {
  1422. this.base = svg.Element.ElementBase;
  1423. this.base(node);
  1424. this.render = function(ctx) {
  1425. // NOOP
  1426. }
  1427. }
  1428. svg.Element.defs.prototype = new svg.Element.ElementBase;
  1429. // base for gradients
  1430. svg.Element.GradientBase = function(node) {
  1431. this.base = svg.Element.ElementBase;
  1432. this.base(node);
  1433. this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');
  1434. this.stops = [];
  1435. for (var i=0; i<this.children.length; i++) {
  1436. var child = this.children[i];
  1437. if (child.type == 'stop') this.stops.push(child);
  1438. }
  1439. this.getGradient = function() {
  1440. // OVERRIDE ME!
  1441. }
  1442. this.createGradient = function(ctx, element, parentOpacityProp) {
  1443. var stopsContainer = this;
  1444. if (this.getHrefAttribute().hasValue()) {
  1445. stopsContainer = this.getHrefAttribute().getDefinition();
  1446. }
  1447. var addParentOpacity = function (color) {
  1448. if (parentOpacityProp.hasValue()) {
  1449. var p = new svg.Property('color', color);
  1450. return p.addOpacity(parentOpacityProp).value;
  1451. }
  1452. return color;
  1453. };
  1454. var g = this.getGradient(ctx, element);
  1455. if (g == null) return addParentOpacity(stopsContainer.stops[stopsContainer.stops.length - 1].color);
  1456. for (var i=0; i<stopsContainer.stops.length; i++) {
  1457. g.addColorStop(stopsContainer.stops[i].offset, addParentOpacity(stopsContainer.stops[i].color));
  1458. }
  1459. if (this.attribute('gradientTransform').hasValue()) {
  1460. // render as transformed pattern on temporary canvas
  1461. var rootView = svg.ViewPort.viewPorts[0];
  1462. var rect = new svg.Element.rect();
  1463. rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS/3.0);
  1464. rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS/3.0);
  1465. rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS);
  1466. rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS);
  1467. var group = new svg.Element.g();
  1468. group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value);
  1469. group.children = [ rect ];
  1470. var tempSvg = new svg.Element.svg();
  1471. tempSvg.attributes['x'] = new svg.Property('x', 0);
  1472. tempSvg.attributes['y'] = new svg.Property('y', 0);
  1473. tempSvg.attributes['width'] = new svg.Property('width', rootView.width);
  1474. tempSvg.attributes['height'] = new svg.Property('height', rootView.height);
  1475. tempSvg.children = [ group ];
  1476. var c = document.createElement('canvas');
  1477. c.width = rootView.width;
  1478. c.height = rootView.height;
  1479. var tempCtx = c.getContext('2d');
  1480. tempCtx.fillStyle = g;
  1481. tempSvg.render(tempCtx);
  1482. return tempCtx.createPattern(c, 'no-repeat');
  1483. }
  1484. return g;
  1485. }
  1486. }
  1487. svg.Element.GradientBase.prototype = new svg.Element.ElementBase;
  1488. // linear gradient element
  1489. svg.Element.linearGradient = function(node) {
  1490. this.base = svg.Element.GradientBase;
  1491. this.base(node);
  1492. this.getGradient = function(ctx, element) {
  1493. var bb = this.gradientUnits == 'objectBoundingBox' ? element.getBoundingBox() : null;
  1494. if (!this.attribute('x1').hasValue()
  1495. && !this.attribute('y1').hasValue()
  1496. && !this.attribute('x2').hasValue()
  1497. && !this.attribute('y2').hasValue()) {
  1498. this.attribute('x1', true).value = 0;
  1499. this.attribute('y1', true).value = 0;
  1500. this.attribute('x2', true).value = 1;
  1501. this.attribute('y2', true).value = 0;
  1502. }
  1503. var x1 = (this.gradientUnits == 'objectBoundingBox'
  1504. ? bb.x() + bb.width() * this.attribute('x1').numValue()
  1505. : this.attribute('x1').toPixels('x'));
  1506. var y1 = (this.gradientUnits == 'objectBoundingBox'
  1507. ? bb.y() + bb.height() * this.attribute('y1').numValue()
  1508. : this.attribute('y1').toPixels('y'));
  1509. var x2 = (this.gradientUnits == 'objectBoundingBox'
  1510. ? bb.x() + bb.width() * this.attribute('x2').numValue()
  1511. : this.attribute('x2').toPixels('x'));
  1512. var y2 = (this.gradientUnits == 'objectBoundingBox'
  1513. ? bb.y() + bb.height() * this.attribute('y2').numValue()
  1514. : this.attribute('y2').toPixels('y'));
  1515. if (x1 == x2 && y1 == y2) return null;
  1516. return ctx.createLinearGradient(x1, y1, x2, y2);
  1517. }
  1518. }
  1519. svg.Element.linearGradient.prototype = new svg.Element.GradientBase;
  1520. // radial gradient element
  1521. svg.Element.radialGradient = function(node) {
  1522. this.base = svg.Element.GradientBase;
  1523. this.base(node);
  1524. this.getGradient = function(ctx, element) {
  1525. var bb = element.getBoundingBox();
  1526. if (!this.attribute('cx').hasValue()) this.attribute('cx', true).value = '50%';
  1527. if (!this.attribute('cy').hasValue()) this.attribute('cy', true).value = '50%';
  1528. if (!this.attribute('r').hasValue()) this.attribute('r', true).value = '50%';
  1529. var cx = (this.gradientUnits == 'objectBoundingBox'
  1530. ? bb.x() + bb.width() * this.attribute('cx').numValue()
  1531. : this.attribute('cx').toPixels('x'));
  1532. var cy = (this.gradientUnits == 'objectBoundingBox'
  1533. ? bb.y() + bb.height() * this.attribute('cy').numValue()
  1534. : this.attribute('cy').toPixels('y'));
  1535. var fx = cx;
  1536. var fy = cy;
  1537. if (this.attribute('fx').hasValue()) {
  1538. fx = (this.gradientUnits == 'objectBoundingBox'
  1539. ? bb.x() + bb.width() * this.attribute('fx').numValue()
  1540. : this.attribute('fx').toPixels('x'));
  1541. }
  1542. if (this.attribute('fy').hasValue()) {
  1543. fy = (this.gradientUnits == 'objectBoundingBox'
  1544. ? bb.y() + bb.height() * this.attribute('fy').numValue()
  1545. : this.attribute('fy').toPixels('y'));
  1546. }
  1547. var r = (this.gradientUnits == 'objectBoundingBox'
  1548. ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue()
  1549. : this.attribute('r').toPixels());
  1550. return ctx.createRadialGradient(fx, fy, 0, cx, cy, r);
  1551. }
  1552. }
  1553. svg.Element.radialGradient.prototype = new svg.Element.GradientBase;
  1554. // gradient stop element
  1555. svg.Element.stop = function(node) {
  1556. this.base = svg.Element.ElementBase;
  1557. this.base(node);
  1558. this.offset = this.attribute('offset').numValue();
  1559. if (this.offset < 0) this.offset = 0;
  1560. if (this.offset > 1) this.offset = 1;
  1561. var stopColor = this.style('stop-color');
  1562. if (this.style('stop-opacity').hasValue()) stopColor = stopColor.addOpacity(this.style('stop-opacity'));
  1563. this.color = stopColor.value;
  1564. }
  1565. svg.Element.stop.prototype = new svg.Element.ElementBase;
  1566. // animation base element
  1567. svg.Element.AnimateBase = function(node) {
  1568. this.base = svg.Element.ElementBase;
  1569. this.base(node);
  1570. svg.Animations.push(this);
  1571. this.duration = 0.0;
  1572. this.begin = this.attribute('begin').toMilliseconds();
  1573. this.maxDuration = this.begin + this.attribute('dur').toMilliseconds();
  1574. this.getProperty = function() {
  1575. var attributeType = this.attribute('attributeType').value;
  1576. var attributeName = this.attribute('attributeName').value;
  1577. if (attributeType == 'CSS') {
  1578. return this.parent.style(attributeName, true);
  1579. }
  1580. return this.parent.attribute(attributeName, true);
  1581. };
  1582. this.initialValue = null;
  1583. this.initialUnits = '';
  1584. this.removed = false;
  1585. this.calcValue = function() {
  1586. // OVERRIDE ME!
  1587. return '';
  1588. }
  1589. this.update = function(delta) {
  1590. // set initial value
  1591. if (this.initialValue == null) {
  1592. this.initialValue = this.getProperty().value;
  1593. this.initialUnits = this.getProperty().getUnits();
  1594. }
  1595. // if we're past the end time
  1596. if (this.duration > this.maxDuration) {
  1597. // loop for indefinitely repeating animations
  1598. if (this.attribute('repeatCount').value == 'indefinite'
  1599. || this.attribute('repeatDur').value == 'indefinite') {
  1600. this.duration = 0.0
  1601. }
  1602. else if (this.attribute('fill').valueOrDefault('remove') == 'freeze' && !this.frozen) {
  1603. this.frozen = true;
  1604. this.parent.animationFrozen = true;
  1605. this.parent.animationFrozenValue = this.getProperty().value;
  1606. }
  1607. else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) {
  1608. this.removed = true;
  1609. this.getProperty().value = this.parent.animationFrozen ? this.parent.animationFrozenValue : this.initialValue;
  1610. return true;
  1611. }
  1612. return false;
  1613. }
  1614. this.duration = this.duration + delta;
  1615. // if we're past the begin time
  1616. var updated = false;
  1617. if (this.begin < this.duration) {
  1618. var newValue = this.calcValue(); // tween
  1619. if (this.attribute('type').hasValue()) {
  1620. // for transform, etc.
  1621. var type = this.attribute('type').value;
  1622. newValue = type + '(' + newValue + ')';
  1623. }
  1624. this.getProperty().value = newValue;
  1625. updated = true;
  1626. }
  1627. return updated;
  1628. }
  1629. this.from = this.attribute('from');
  1630. this.to = this.attribute('to');
  1631. this.values = this.attribute('values');
  1632. if (this.values.hasValue()) this.values.value = this.values.value.split(';');
  1633. // fraction of duration we've covered
  1634. this.progress = function() {
  1635. var ret = { progress: (this.duration - this.begin) / (this.maxDuration - this.begin) };
  1636. if (this.values.hasValue()) {
  1637. var p = ret.progress * (this.values.value.length - 1);
  1638. var lb = Math.floor(p), ub = Math.ceil(p);
  1639. ret.from = new svg.Property('from', parseFloat(this.values.value[lb]));
  1640. ret.to = new svg.Property('to', parseFloat(this.values.value[ub]));
  1641. ret.progress = (p - lb) / (ub - lb);
  1642. }
  1643. else {
  1644. ret.from = this.from;
  1645. ret.to = this.to;
  1646. }
  1647. return ret;
  1648. }
  1649. }
  1650. svg.Element.AnimateBase.prototype = new svg.Element.ElementBase;
  1651. // animate element
  1652. svg.Element.animate = function(node) {
  1653. this.base = svg.Element.AnimateBase;
  1654. this.base(node);
  1655. this.calcValue = function() {
  1656. var p = this.progress();
  1657. // tween value linearly
  1658. var newValue = p.from.numValue() + (p.to.numValue() - p.from.numValue()) * p.progress;
  1659. return newValue + this.initialUnits;
  1660. };
  1661. }
  1662. svg.Element.animate.prototype = new svg.Element.AnimateBase;
  1663. // animate color element
  1664. svg.Element.animateColor = function(node) {
  1665. this.base = svg.Element.AnimateBase;
  1666. this.base(node);
  1667. this.calcValue = function() {
  1668. var p = this.progress();
  1669. var from = new RGBColor(p.from.value);
  1670. var to = new RGBColor(p.to.value);
  1671. if (from.ok && to.ok) {
  1672. // tween color linearly
  1673. var r = from.r + (to.r - from.r) * p.progress;
  1674. var g = from.g + (to.g - from.g) * p.progress;
  1675. var b = from.b + (to.b - from.b) * p.progress;
  1676. return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')';
  1677. }
  1678. return this.attribute('from').value;
  1679. };
  1680. }
  1681. svg.Element.animateColor.prototype = new svg.Element.AnimateBase;
  1682. // animate transform element
  1683. svg.Element.animateTransform = function(node) {
  1684. this.base = svg.Element.AnimateBase;
  1685. this.base(node);
  1686. this.calcValue = function() {
  1687. var p = this.progress();
  1688. // tween value linearly
  1689. var from = svg.ToNumberArray(p.from.value);
  1690. var to = svg.ToNumberArray(p.to.value);
  1691. var newValue = '';
  1692. for (var i=0; i<from.length; i++) {
  1693. newValue += from[i] + (to[i] - from[i]) * p.progress + ' ';
  1694. }
  1695. return newValue;
  1696. };
  1697. }
  1698. svg.Element.animateTransform.prototype = new svg.Element.animate;
  1699. // font element
  1700. svg.Element.font = function(node) {
  1701. this.base = svg.Element.ElementBase;
  1702. this.base(node);
  1703. this.horizAdvX = this.attribute('horiz-adv-x').numValue();
  1704. this.isRTL = false;
  1705. this.isArabic = false;
  1706. this.fontFace = null;
  1707. this.missingGlyph = null;
  1708. this.glyphs = [];
  1709. for (var i=0; i<this.children.length; i++) {
  1710. var child = this.children[i];
  1711. if (child.type == 'font-face') {
  1712. this.fontFace = child;
  1713. if (child.style('font-family').hasValue()) {
  1714. svg.Definitions[child.style('font-family').value] = this;
  1715. }
  1716. }
  1717. else if (child.type == 'missing-glyph') this.missingGlyph = child;
  1718. else if (child.type == 'glyph') {
  1719. if (child.arabicForm != '') {
  1720. this.isRTL = true;
  1721. this.isArabic = true;
  1722. if (typeof(this.glyphs[child.unicode]) == 'undefined') this.glyphs[child.unicode] = [];
  1723. this.glyphs[child.unicode][child.arabicForm] = child;
  1724. }
  1725. else {
  1726. this.glyphs[child.unicode] = child;
  1727. }
  1728. }
  1729. }
  1730. }
  1731. svg.Element.font.prototype = new svg.Element.ElementBase;
  1732. // font-face element
  1733. svg.Element.fontface = function(node) {
  1734. this.base = svg.Element.ElementBase;
  1735. this.base(node);
  1736. this.ascent = this.attribute('ascent').value;
  1737. this.descent = this.attribute('descent').value;
  1738. this.unitsPerEm = this.attribute('units-per-em').numValue();
  1739. }
  1740. svg.Element.fontface.prototype = new svg.Element.ElementBase;
  1741. // missing-glyph element
  1742. svg.Element.missingglyph = function(node) {
  1743. this.base = svg.Element.path;
  1744. this.base(node);
  1745. this.horizAdvX = 0;
  1746. }
  1747. svg.Element.missingglyph.prototype = new svg.Element.path;
  1748. // glyph element
  1749. svg.Element.glyph = function(node) {
  1750. this.base = svg.Element.path;
  1751. this.base(node);
  1752. this.horizAdvX = this.attribute('horiz-adv-x').numValue();
  1753. this.unicode = this.attribute('unicode').value;
  1754. this.arabicForm = this.attribute('arabic-form').value;
  1755. }
  1756. svg.Element.glyph.prototype = new svg.Element.path;
  1757. // text element
  1758. svg.Element.text = function(node) {
  1759. this.captureTextNodes = true;
  1760. this.base = svg.Element.RenderedElementBase;
  1761. this.base(node);
  1762. this.baseSetContext = this.setContext;
  1763. this.setContext = function(ctx) {
  1764. this.baseSetContext(ctx);
  1765. var textBaseline = this.style('dominant-baseline').toTextBaseline();
  1766. if (textBaseline == null) textBaseline = this.style('alignment-baseline').toTextBaseline();
  1767. if (textBaseline != null) ctx.textBaseline = textBaseline;
  1768. }
  1769. this.getBoundingBox = function () {
  1770. var x = this.attribute('x').toPixels('x');
  1771. var y = this.attribute('y').toPixels('y');
  1772. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  1773. return new svg.BoundingBox(x, y - fontSize, x + Math.floor(fontSize * 2.0 / 3.0) * this.children[0].getText().length, y);
  1774. }
  1775. this.renderChildren = function(ctx) {
  1776. this.x = this.attribute('x').toPixels('x');
  1777. this.y = this.attribute('y').toPixels('y');
  1778. this.x += this.getAnchorDelta(ctx, this, 0);
  1779. for (var i=0; i<this.children.length; i++) {
  1780. this.renderChild(ctx, this, i);
  1781. }
  1782. }
  1783. this.getAnchorDelta = function (ctx, parent, startI) {
  1784. var textAnchor = this.style('text-anchor').valueOrDefault('start');
  1785. if (textAnchor != 'start') {
  1786. var width = 0;
  1787. for (var i=startI; i<parent.children.length; i++) {
  1788. var child = parent.children[i];
  1789. if (i > startI && child.attribute('x').hasValue()) break; // new group
  1790. width += child.measureTextRecursive(ctx);
  1791. }
  1792. return -1 * (textAnchor == 'end' ? width : width / 2.0);
  1793. }
  1794. return 0;
  1795. }
  1796. this.renderChild = function(ctx, parent, i) {
  1797. var child = parent.children[i];
  1798. if (child.attribute('x').hasValue()) {
  1799. child.x = child.attribute('x').toPixels('x') + this.getAnchorDelta(ctx, parent, i);
  1800. if (child.attribute('dx').hasValue()) child.x += child.attribute('dx').toPixels('x');
  1801. }
  1802. else {
  1803. if (this.attribute('dx').hasValue()) this.x += this.attribute('dx').toPixels('x');
  1804. if (child.attribute('dx').hasValue()) this.x += child.attribute('dx').toPixels('x');
  1805. child.x = this.x;
  1806. }
  1807. this.x = child.x + child.measureText(ctx);
  1808. if (child.attribute('y').hasValue()) {
  1809. child.y = child.attribute('y').toPixels('y');
  1810. if (child.attribute('dy').hasValue()) child.y += child.attribute('dy').toPixels('y');
  1811. }
  1812. else {
  1813. if (this.attribute('dy').hasValue()) this.y += this.attribute('dy').toPixels('y');
  1814. if (child.attribute('dy').hasValue()) this.y += child.attribute('dy').toPixels('y');
  1815. child.y = this.y;
  1816. }
  1817. this.y = child.y;
  1818. child.render(ctx);
  1819. for (var i=0; i<child.children.length; i++) {
  1820. this.renderChild(ctx, child, i);
  1821. }
  1822. }
  1823. }
  1824. svg.Element.text.prototype = new svg.Element.RenderedElementBase;
  1825. // text base
  1826. svg.Element.TextElementBase = function(node) {
  1827. this.base = svg.Element.RenderedElementBase;
  1828. this.base(node);
  1829. this.getGlyph = function(font, text, i) {
  1830. var c = text[i];
  1831. var glyph = null;
  1832. if (font.isArabic) {
  1833. var arabicForm = 'isolated';
  1834. if ((i==0 || text[i-1]==' ') && i<text.length-2 && text[i+1]!=' ') arabicForm = 'terminal';
  1835. if (i>0 && text[i-1]!=' ' && i<text.length-2 && text[i+1]!=' ') arabicForm = 'medial';
  1836. if (i>0 && text[i-1]!=' ' && (i == text.length-1 || text[i+1]==' ')) arabicForm = 'initial';
  1837. if (typeof(font.glyphs[c]) != 'undefined') {
  1838. glyph = font.glyphs[c][arabicForm];
  1839. if (glyph == null && font.glyphs[c].type == 'glyph') glyph = font.glyphs[c];
  1840. }
  1841. }
  1842. else {
  1843. glyph = font.glyphs[c];
  1844. }
  1845. if (glyph == null) glyph = font.missingGlyph;
  1846. return glyph;
  1847. }
  1848. this.renderChildren = function(ctx) {
  1849. var customFont = this.parent.style('font-family').getDefinition();
  1850. if (customFont != null) {
  1851. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  1852. var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle);
  1853. var text = this.getText();
  1854. if (customFont.isRTL) text = text.split("").reverse().join("");
  1855. var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
  1856. for (var i=0; i<text.length; i++) {
  1857. var glyph = this.getGlyph(customFont, text, i);
  1858. var scale = fontSize / customFont.fontFace.unitsPerEm;
  1859. ctx.translate(this.x, this.y);
  1860. ctx.scale(scale, -scale);
  1861. var lw = ctx.lineWidth;
  1862. ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize;
  1863. if (fontStyle == 'italic') ctx.transform(1, 0, .4, 1, 0, 0);
  1864. glyph.render(ctx);
  1865. if (fontStyle == 'italic') ctx.transform(1, 0, -.4, 1, 0, 0);
  1866. ctx.lineWidth = lw;
  1867. ctx.scale(1/scale, -1/scale);
  1868. ctx.translate(-this.x, -this.y);
  1869. this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm;
  1870. if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) {
  1871. this.x += dx[i];
  1872. }
  1873. }
  1874. return;
  1875. }
  1876. if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
  1877. if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y);
  1878. }
  1879. this.getText = function() {
  1880. // OVERRIDE ME
  1881. }
  1882. this.measureTextRecursive = function(ctx) {
  1883. var width = this.measureText(ctx);
  1884. for (var i=0; i<this.children.length; i++) {
  1885. width += this.children[i].measureTextRecursive(ctx);
  1886. }
  1887. return width;
  1888. }
  1889. this.measureText = function(ctx) {
  1890. var customFont = this.parent.style('font-family').getDefinition();
  1891. if (customFont != null) {
  1892. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  1893. var measure = 0;
  1894. var text = this.getText();
  1895. if (customFont.isRTL) text = text.split("").reverse().join("");
  1896. var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
  1897. for (var i=0; i<text.length; i++) {
  1898. var glyph = this.getGlyph(customFont, text, i);
  1899. measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm;
  1900. if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) {
  1901. measure += dx[i];
  1902. }
  1903. }
  1904. return measure;
  1905. }
  1906. var textToMeasure = svg.compressSpaces(this.getText());
  1907. if (!ctx.measureText) return textToMeasure.length * 10;
  1908. ctx.save();
  1909. this.setContext(ctx);
  1910. var width = ctx.measureText(textToMeasure).width;
  1911. ctx.restore();
  1912. return width;
  1913. }
  1914. }
  1915. svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase;
  1916. // tspan
  1917. svg.Element.tspan = function(node) {
  1918. this.captureTextNodes = true;
  1919. this.base = svg.Element.TextElementBase;
  1920. this.base(node);
  1921. this.text = node.nodeValue || node.text || '';
  1922. this.getText = function() {
  1923. return this.text;
  1924. }
  1925. }
  1926. svg.Element.tspan.prototype = new svg.Element.TextElementBase;
  1927. // tref
  1928. svg.Element.tref = function(node) {
  1929. this.base = svg.Element.TextElementBase;
  1930. this.base(node);
  1931. this.getText = function() {
  1932. var element = this.getHrefAttribute().getDefinition();
  1933. if (element != null) return element.children[0].getText();
  1934. }
  1935. }
  1936. svg.Element.tref.prototype = new svg.Element.TextElementBase;
  1937. // a element
  1938. svg.Element.a = function(node) {
  1939. this.base = svg.Element.TextElementBase;
  1940. this.base(node);
  1941. this.hasText = true;
  1942. for (var i=0; i<node.childNodes.length; i++) {
  1943. if (node.childNodes[i].nodeType != 3) this.hasText = false;
  1944. }
  1945. // this might contain text
  1946. this.text = this.hasText ? node.childNodes[0].nodeValue : '';
  1947. this.getText = function() {
  1948. return this.text;
  1949. }
  1950. this.baseRenderChildren = this.renderChildren;
  1951. this.renderChildren = function(ctx) {
  1952. if (this.hasText) {
  1953. // render as text element
  1954. this.baseRenderChildren(ctx);
  1955. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  1956. svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.toPixels('y'), this.x + this.measureText(ctx), this.y));
  1957. }
  1958. else {
  1959. // render as temporary group
  1960. var g = new svg.Element.g();
  1961. g.children = this.children;
  1962. g.parent = this;
  1963. g.render(ctx);
  1964. }
  1965. }
  1966. this.onclick = function() {
  1967. window.open(this.getHrefAttribute().value);
  1968. }
  1969. this.onmousemove = function() {
  1970. svg.ctx.canvas.style.cursor = 'pointer';
  1971. }
  1972. }
  1973. svg.Element.a.prototype = new svg.Element.TextElementBase;
  1974. // image element
  1975. svg.Element.image = function(node) {
  1976. this.base = svg.Element.RenderedElementBase;
  1977. this.base(node);
  1978. var href = this.getHrefAttribute().value;
  1979. if (href === '') {
  1980. return;
  1981. }
  1982. var isSvg = href.match(/\.svg$/)
  1983. svg.Images.push(this);
  1984. this.loaded = false;
  1985. if (!isSvg) {
  1986. this.img = document.createElement('img');
  1987. if (svg.opts['useCORS'] == true) { this.img.crossOrigin = 'Anonymous'; }
  1988. var self = this;
  1989. this.img.onload = function() { self.loaded = true; }
  1990. this.img.onerror = function() { svg.log('ERROR: image "' + href + '" not found'); self.loaded = true; }
  1991. this.img.src = href;
  1992. }
  1993. else {
  1994. this.img = svg.ajax(href);
  1995. this.loaded = true;
  1996. }
  1997. this.renderChildren = function(ctx) {
  1998. var x = this.attribute('x').toPixels('x');
  1999. var y = this.attribute('y').toPixels('y');
  2000. var width = this.attribute('width').toPixels('x');
  2001. var height = this.attribute('height').toPixels('y');
  2002. if (width == 0 || height == 0) return;
  2003. ctx.save();
  2004. if (isSvg) {
  2005. ctx.drawSvg(this.img, x, y, width, height);
  2006. }
  2007. else {
  2008. ctx.translate(x, y);
  2009. svg.AspectRatio(ctx,
  2010. this.attribute('preserveAspectRatio').value,
  2011. width,
  2012. this.img.width,
  2013. height,
  2014. this.img.height,
  2015. 0,
  2016. 0);
  2017. ctx.drawImage(this.img, 0, 0);
  2018. }
  2019. ctx.restore();
  2020. }
  2021. this.getBoundingBox = function() {
  2022. var x = this.attribute('x').toPixels('x');
  2023. var y = this.attribute('y').toPixels('y');
  2024. var width = this.attribute('width').toPixels('x');
  2025. var height = this.attribute('height').toPixels('y');
  2026. return new svg.BoundingBox(x, y, x + width, y + height);
  2027. }
  2028. }
  2029. svg.Element.image.prototype = new svg.Element.RenderedElementBase;
  2030. // group element
  2031. svg.Element.g = function(node) {
  2032. this.base = svg.Element.RenderedElementBase;
  2033. this.base(node);
  2034. this.getBoundingBox = function() {
  2035. var bb = new svg.BoundingBox();
  2036. for (var i=0; i<this.children.length; i++) {
  2037. bb.addBoundingBox(this.children[i].getBoundingBox());
  2038. }
  2039. return bb;
  2040. };
  2041. }
  2042. svg.Element.g.prototype = new svg.Element.RenderedElementBase;
  2043. // symbol element
  2044. svg.Element.symbol = function(node) {
  2045. this.base = svg.Element.RenderedElementBase;
  2046. this.base(node);
  2047. this.render = function(ctx) {
  2048. // NO RENDER
  2049. };
  2050. }
  2051. svg.Element.symbol.prototype = new svg.Element.RenderedElementBase;
  2052. // style element
  2053. svg.Element.style = function(node) {
  2054. this.base = svg.Element.ElementBase;
  2055. this.base(node);
  2056. // text, or spaces then CDATA
  2057. var css = ''
  2058. for (var i=0; i<node.childNodes.length; i++) {
  2059. css += node.childNodes[i].nodeValue;
  2060. }
  2061. css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(^[\s]*\/\/.*)/gm, ''); // remove comments
  2062. css = svg.compressSpaces(css); // replace whitespace
  2063. var cssDefs = css.split('}');
  2064. for (var i=0; i<cssDefs.length; i++) {
  2065. if (svg.trim(cssDefs[i]) != '') {
  2066. var cssDef = cssDefs[i].split('{');
  2067. var cssClasses = cssDef[0].split(',');
  2068. var cssProps = cssDef[1].split(';');
  2069. for (var j=0; j<cssClasses.length; j++) {
  2070. var cssClass = svg.trim(cssClasses[j]);
  2071. if (cssClass != '') {
  2072. var props = {};
  2073. for (var k=0; k<cssProps.length; k++) {
  2074. var prop = cssProps[k].indexOf(':');
  2075. var name = cssProps[k].substr(0, prop);
  2076. var value = cssProps[k].substr(prop + 1, cssProps[k].length - prop);
  2077. if (name != null && value != null) {
  2078. props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value));
  2079. }
  2080. }
  2081. svg.Styles[cssClass] = props;
  2082. if (cssClass == '@font-face') {
  2083. var fontFamily = props['font-family'].value.replace(/"/g,'');
  2084. var srcs = props['src'].value.split(',');
  2085. for (var s=0; s<srcs.length; s++) {
  2086. if (srcs[s].indexOf('format("svg")') > 0) {
  2087. var urlStart = srcs[s].indexOf('url');
  2088. var urlEnd = srcs[s].indexOf(')', urlStart);
  2089. var url = srcs[s].substr(urlStart + 5, urlEnd - urlStart - 6);
  2090. var doc = svg.parseXml(svg.ajax(url));
  2091. var fonts = doc.getElementsByTagName('font');
  2092. for (var f=0; f<fonts.length; f++) {
  2093. var font = svg.CreateElement(fonts[f]);
  2094. svg.Definitions[fontFamily] = font;
  2095. }
  2096. }
  2097. }
  2098. }
  2099. }
  2100. }
  2101. }
  2102. }
  2103. }
  2104. svg.Element.style.prototype = new svg.Element.ElementBase;
  2105. // use element
  2106. svg.Element.use = function(node) {
  2107. this.base = svg.Element.RenderedElementBase;
  2108. this.base(node);
  2109. this.baseSetContext = this.setContext;
  2110. this.setContext = function(ctx) {
  2111. this.baseSetContext(ctx);
  2112. if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').toPixels('x'), 0);
  2113. if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').toPixels('y'));
  2114. }
  2115. var element = this.getHrefAttribute().getDefinition();
  2116. this.path = function(ctx) {
  2117. if (element != null) element.path(ctx);
  2118. }
  2119. this.getBoundingBox = function() {
  2120. if (element != null) return element.getBoundingBox();
  2121. }
  2122. this.renderChildren = function(ctx) {
  2123. if (element != null) {
  2124. var tempSvg = element;
  2125. if (element.type == 'symbol') {
  2126. // render me using a temporary svg element in symbol cases (http://www.w3.org/TR/SVG/struct.html#UseElement)
  2127. tempSvg = new svg.Element.svg();
  2128. tempSvg.type = 'svg';
  2129. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', element.attribute('viewBox').value);
  2130. tempSvg.attributes['preserveAspectRatio'] = new svg.Property('preserveAspectRatio', element.attribute('preserveAspectRatio').value);
  2131. tempSvg.attributes['overflow'] = new svg.Property('overflow', element.attribute('overflow').value);
  2132. tempSvg.children = element.children;
  2133. }
  2134. if (tempSvg.type == 'svg') {
  2135. // if symbol or svg, inherit width/height from me
  2136. if (this.attribute('width').hasValue()) tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);
  2137. if (this.attribute('height').hasValue()) tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);
  2138. }
  2139. var oldParent = tempSvg.parent;
  2140. tempSvg.parent = null;
  2141. tempSvg.render(ctx);
  2142. tempSvg.parent = oldParent;
  2143. }
  2144. }
  2145. }
  2146. svg.Element.use.prototype = new svg.Element.RenderedElementBase;
  2147. // mask element
  2148. svg.Element.mask = function(node) {
  2149. this.base = svg.Element.ElementBase;
  2150. this.base(node);
  2151. this.apply = function(ctx, element) {
  2152. // render as temp svg
  2153. var x = this.attribute('x').toPixels('x');
  2154. var y = this.attribute('y').toPixels('y');
  2155. var width = this.attribute('width').toPixels('x');
  2156. var height = this.attribute('height').toPixels('y');
  2157. if (width == 0 && height == 0) {
  2158. var bb = new svg.BoundingBox();
  2159. for (var i=0; i<this.children.length; i++) {
  2160. bb.addBoundingBox(this.children[i].getBoundingBox());
  2161. }
  2162. var x = Math.floor(bb.x1);
  2163. var y = Math.floor(bb.y1);
  2164. var width = Math.floor(bb.width());
  2165. var height = Math.floor(bb.height());
  2166. }
  2167. // temporarily remove mask to avoid recursion
  2168. var mask = element.attribute('mask').value;
  2169. element.attribute('mask').value = '';
  2170. var cMask = document.createElement('canvas');
  2171. cMask.width = x + width;
  2172. cMask.height = y + height;
  2173. var maskCtx = cMask.getContext('2d');
  2174. this.renderChildren(maskCtx);
  2175. var c = document.createElement('canvas');
  2176. c.width = x + width;
  2177. c.height = y + height;
  2178. var tempCtx = c.getContext('2d');
  2179. element.render(tempCtx);
  2180. tempCtx.globalCompositeOperation = 'destination-in';
  2181. tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat');
  2182. tempCtx.fillRect(0, 0, x + width, y + height);
  2183. ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat');
  2184. ctx.fillRect(0, 0, x + width, y + height);
  2185. // reassign mask
  2186. element.attribute('mask').value = mask;
  2187. }
  2188. this.render = function(ctx) {
  2189. // NO RENDER
  2190. }
  2191. }
  2192. svg.Element.mask.prototype = new svg.Element.ElementBase;
  2193. // clip element
  2194. svg.Element.clipPath = function(node) {
  2195. this.base = svg.Element.ElementBase;
  2196. this.base(node);
  2197. this.apply = function(ctx) {
  2198. for (var i=0; i<this.children.length; i++) {
  2199. var child = this.children[i];
  2200. if (typeof(child.path) != 'undefined') {
  2201. var transform = null;
  2202. if (child.attribute('transform').hasValue()) {
  2203. transform = new svg.Transform(child.attribute('transform').value);
  2204. transform.apply(ctx);
  2205. }
  2206. child.path(ctx);
  2207. ctx.clip();
  2208. if (transform) { transform.unapply(ctx); }
  2209. }
  2210. }
  2211. }
  2212. this.render = function(ctx) {
  2213. // NO RENDER
  2214. }
  2215. }
  2216. svg.Element.clipPath.prototype = new svg.Element.ElementBase;
  2217. // filters
  2218. svg.Element.filter = function(node) {
  2219. this.base = svg.Element.ElementBase;
  2220. this.base(node);
  2221. this.apply = function(ctx, element) {
  2222. // render as temp svg
  2223. var bb = element.getBoundingBox();
  2224. var x = Math.floor(bb.x1);
  2225. var y = Math.floor(bb.y1);
  2226. var width = Math.floor(bb.width());
  2227. var height = Math.floor(bb.height());
  2228. // temporarily remove filter to avoid recursion
  2229. var filter = element.style('filter').value;
  2230. element.style('filter').value = '';
  2231. var px = 0, py = 0;
  2232. for (var i=0; i<this.children.length; i++) {
  2233. var efd = this.children[i].extraFilterDistance || 0;
  2234. px = Math.max(px, efd);
  2235. py = Math.max(py, efd);
  2236. }
  2237. var c = document.createElement('canvas');
  2238. c.width = width + 2*px;
  2239. c.height = height + 2*py;
  2240. var tempCtx = c.getContext('2d');
  2241. tempCtx.translate(-x + px, -y + py);
  2242. element.render(tempCtx);
  2243. // apply filters
  2244. for (var i=0; i<this.children.length; i++) {
  2245. this.children[i].apply(tempCtx, 0, 0, width + 2*px, height + 2*py);
  2246. }
  2247. // render on me
  2248. ctx.drawImage(c, 0, 0, width + 2*px, height + 2*py, x - px, y - py, width + 2*px, height + 2*py);
  2249. // reassign filter
  2250. element.style('filter', true).value = filter;
  2251. }
  2252. this.render = function(ctx) {
  2253. // NO RENDER
  2254. }
  2255. }
  2256. svg.Element.filter.prototype = new svg.Element.ElementBase;
  2257. svg.Element.feMorphology = function(node) {
  2258. this.base = svg.Element.ElementBase;
  2259. this.base(node);
  2260. this.apply = function(ctx, x, y, width, height) {
  2261. // TODO: implement
  2262. }
  2263. }
  2264. svg.Element.feMorphology.prototype = new svg.Element.ElementBase;
  2265. svg.Element.feComposite = function(node) {
  2266. this.base = svg.Element.ElementBase;
  2267. this.base(node);
  2268. this.apply = function(ctx, x, y, width, height) {
  2269. // TODO: implement
  2270. }
  2271. }
  2272. svg.Element.feComposite.prototype = new svg.Element.ElementBase;
  2273. svg.Element.feColorMatrix = function(node) {
  2274. this.base = svg.Element.ElementBase;
  2275. this.base(node);
  2276. var matrix = svg.ToNumberArray(this.attribute('values').value);
  2277. switch (this.attribute('type').valueOrDefault('matrix')) { // http://www.w3.org/TR/SVG/filters.html#feColorMatrixElement
  2278. case 'saturate':
  2279. var s = matrix[0];
  2280. matrix = [0.213+0.787*s,0.715-0.715*s,0.072-0.072*s,0,0,
  2281. 0.213-0.213*s,0.715+0.285*s,0.072-0.072*s,0,0,
  2282. 0.213-0.213*s,0.715-0.715*s,0.072+0.928*s,0,0,
  2283. 0,0,0,1,0,
  2284. 0,0,0,0,1];
  2285. break;
  2286. case 'hueRotate':
  2287. var a = matrix[0] * Math.PI / 180.0;
  2288. var c = function (m1,m2,m3) { return m1 + Math.cos(a)*m2 + Math.sin(a)*m3; };
  2289. matrix = [c(0.213,0.787,-0.213),c(0.715,-0.715,-0.715),c(0.072,-0.072,0.928),0,0,
  2290. c(0.213,-0.213,0.143),c(0.715,0.285,0.140),c(0.072,-0.072,-0.283),0,0,
  2291. c(0.213,-0.213,-0.787),c(0.715,-0.715,0.715),c(0.072,0.928,0.072),0,0,
  2292. 0,0,0,1,0,
  2293. 0,0,0,0,1];
  2294. break;
  2295. case 'luminanceToAlpha':
  2296. matrix = [0,0,0,0,0,
  2297. 0,0,0,0,0,
  2298. 0,0,0,0,0,
  2299. 0.2125,0.7154,0.0721,0,0,
  2300. 0,0,0,0,1];
  2301. break;
  2302. }
  2303. function imGet(img, x, y, width, height, rgba) {
  2304. return img[y*width*4 + x*4 + rgba];
  2305. }
  2306. function imSet(img, x, y, width, height, rgba, val) {
  2307. img[y*width*4 + x*4 + rgba] = val;
  2308. }
  2309. function m(i, v) {
  2310. var mi = matrix[i];
  2311. return mi * (mi < 0 ? v - 255 : v);
  2312. }
  2313. this.apply = function(ctx, x, y, width, height) {
  2314. // assuming x==0 && y==0 for now
  2315. var srcData = ctx.getImageData(0, 0, width, height);
  2316. for (var y = 0; y < height; y++) {
  2317. for (var x = 0; x < width; x++) {
  2318. var r = imGet(srcData.data, x, y, width, height, 0);
  2319. var g = imGet(srcData.data, x, y, width, height, 1);
  2320. var b = imGet(srcData.data, x, y, width, height, 2);
  2321. var a = imGet(srcData.data, x, y, width, height, 3);
  2322. imSet(srcData.data, x, y, width, height, 0, m(0,r)+m(1,g)+m(2,b)+m(3,a)+m(4,1));
  2323. imSet(srcData.data, x, y, width, height, 1, m(5,r)+m(6,g)+m(7,b)+m(8,a)+m(9,1));
  2324. imSet(srcData.data, x, y, width, height, 2, m(10,r)+m(11,g)+m(12,b)+m(13,a)+m(14,1));
  2325. imSet(srcData.data, x, y, width, height, 3, m(15,r)+m(16,g)+m(17,b)+m(18,a)+m(19,1));
  2326. }
  2327. }
  2328. ctx.clearRect(0, 0, width, height);
  2329. ctx.putImageData(srcData, 0, 0);
  2330. }
  2331. }
  2332. svg.Element.feColorMatrix.prototype = new svg.Element.ElementBase;
  2333. svg.Element.feGaussianBlur = function(node) {
  2334. this.base = svg.Element.ElementBase;
  2335. this.base(node);
  2336. this.blurRadius = Math.floor(this.attribute('stdDeviation').numValue());
  2337. this.extraFilterDistance = this.blurRadius;
  2338. this.apply = function(ctx, x, y, width, height) {
  2339. if (typeof(stackBlurCanvasRGBA) == 'undefined') {
  2340. svg.log('ERROR: StackBlur.js must be included for blur to work');
  2341. return;
  2342. }
  2343. // StackBlur requires canvas be on document
  2344. ctx.canvas.id = svg.UniqueId();
  2345. ctx.canvas.style.display = 'none';
  2346. document.body.appendChild(ctx.canvas);
  2347. stackBlurCanvasRGBA(ctx.canvas.id, x, y, width, height, this.blurRadius);
  2348. document.body.removeChild(ctx.canvas);
  2349. }
  2350. }
  2351. svg.Element.feGaussianBlur.prototype = new svg.Element.ElementBase;
  2352. // title element, do nothing
  2353. svg.Element.title = function(node) {
  2354. }
  2355. svg.Element.title.prototype = new svg.Element.ElementBase;
  2356. // desc element, do nothing
  2357. svg.Element.desc = function(node) {
  2358. }
  2359. svg.Element.desc.prototype = new svg.Element.ElementBase;
  2360. svg.Element.MISSING = function(node) {
  2361. svg.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.');
  2362. }
  2363. svg.Element.MISSING.prototype = new svg.Element.ElementBase;
  2364. // element factory
  2365. svg.CreateElement = function(node) {
  2366. var className = node.nodeName.replace(/^[^:]+:/,''); // remove namespace
  2367. className = className.replace(/\-/g,''); // remove dashes
  2368. var e = null;
  2369. if (typeof(svg.Element[className]) != 'undefined') {
  2370. e = new svg.Element[className](node);
  2371. }
  2372. else {
  2373. e = new svg.Element.MISSING(node);
  2374. }
  2375. e.type = node.nodeName;
  2376. return e;
  2377. }
  2378. // load from url
  2379. svg.load = function(ctx, url) {
  2380. svg.loadXml(ctx, svg.ajax(url));
  2381. }
  2382. // load from xml
  2383. svg.loadXml = function(ctx, xml) {
  2384. svg.loadXmlDoc(ctx, svg.parseXml(xml));
  2385. }
  2386. svg.loadXmlDoc = function(ctx, dom) {
  2387. svg.init(ctx);
  2388. var mapXY = function(p) {
  2389. var e = ctx.canvas;
  2390. while (e) {
  2391. p.x -= e.offsetLeft;
  2392. p.y -= e.offsetTop;
  2393. e = e.offsetParent;
  2394. }
  2395. if (window.scrollX) p.x += window.scrollX;
  2396. if (window.scrollY) p.y += window.scrollY;
  2397. return p;
  2398. }
  2399. // bind mouse
  2400. if (svg.opts['ignoreMouse'] != true) {
  2401. ctx.canvas.onclick = function(e) {
  2402. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  2403. svg.Mouse.onclick(p.x, p.y);
  2404. };
  2405. ctx.canvas.onmousemove = function(e) {
  2406. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  2407. svg.Mouse.onmousemove(p.x, p.y);
  2408. };
  2409. }
  2410. var e = svg.CreateElement(dom.documentElement);
  2411. e.root = true;
  2412. // render loop
  2413. var isFirstRender = true;
  2414. var draw = function() {
  2415. svg.ViewPort.Clear();
  2416. if (ctx.canvas.parentNode) svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight);
  2417. if (svg.opts['ignoreDimensions'] != true) {
  2418. // set canvas size
  2419. if (e.style('width').hasValue()) {
  2420. ctx.canvas.width = e.style('width').toPixels('x');
  2421. ctx.canvas.style.width = ctx.canvas.width + 'px';
  2422. }
  2423. if (e.style('height').hasValue()) {
  2424. ctx.canvas.height = e.style('height').toPixels('y');
  2425. ctx.canvas.style.height = ctx.canvas.height + 'px';
  2426. }
  2427. }
  2428. var cWidth = ctx.canvas.clientWidth || ctx.canvas.width;
  2429. var cHeight = ctx.canvas.clientHeight || ctx.canvas.height;
  2430. if (svg.opts['ignoreDimensions'] == true && e.style('width').hasValue() && e.style('height').hasValue()) {
  2431. cWidth = e.style('width').toPixels('x');
  2432. cHeight = e.style('height').toPixels('y');
  2433. }
  2434. svg.ViewPort.SetCurrent(cWidth, cHeight);
  2435. if (svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX'];
  2436. if (svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY'];
  2437. if (svg.opts['scaleWidth'] != null || svg.opts['scaleHeight'] != null) {
  2438. var xRatio = null, yRatio = null, viewBox = svg.ToNumberArray(e.attribute('viewBox').value);
  2439. if (svg.opts['scaleWidth'] != null) {
  2440. if (e.attribute('width').hasValue()) xRatio = e.attribute('width').toPixels('x') / svg.opts['scaleWidth'];
  2441. else if (!isNaN(viewBox[2])) xRatio = viewBox[2] / svg.opts['scaleWidth'];
  2442. }
  2443. if (svg.opts['scaleHeight'] != null) {
  2444. if (e.attribute('height').hasValue()) yRatio = e.attribute('height').toPixels('y') / svg.opts['scaleHeight'];
  2445. else if (!isNaN(viewBox[3])) yRatio = viewBox[3] / svg.opts['scaleHeight'];
  2446. }
  2447. if (xRatio == null) { xRatio = yRatio; }
  2448. if (yRatio == null) { yRatio = xRatio; }
  2449. e.attribute('width', true).value = svg.opts['scaleWidth'];
  2450. e.attribute('height', true).value = svg.opts['scaleHeight'];
  2451. e.attribute('viewBox', true).value = '0 0 ' + (cWidth * xRatio) + ' ' + (cHeight * yRatio);
  2452. e.attribute('preserveAspectRatio', true).value = 'none';
  2453. }
  2454. // clear and render
  2455. if (svg.opts['ignoreClear'] != true) {
  2456. ctx.clearRect(0, 0, cWidth, cHeight);
  2457. }
  2458. e.render(ctx);
  2459. if (isFirstRender) {
  2460. isFirstRender = false;
  2461. if (typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback'](dom);
  2462. }
  2463. }
  2464. var waitingForImages = true;
  2465. if (svg.ImagesLoaded()) {
  2466. waitingForImages = false;
  2467. draw();
  2468. }
  2469. svg.intervalID = setInterval(function() {
  2470. var needUpdate = false;
  2471. if (waitingForImages && svg.ImagesLoaded()) {
  2472. waitingForImages = false;
  2473. needUpdate = true;
  2474. }
  2475. // need update from mouse events?
  2476. if (svg.opts['ignoreMouse'] != true) {
  2477. needUpdate = needUpdate | svg.Mouse.hasEvents();
  2478. }
  2479. // need update from animations?
  2480. if (svg.opts['ignoreAnimation'] != true) {
  2481. for (var i=0; i<svg.Animations.length; i++) {
  2482. needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE);
  2483. }
  2484. }
  2485. // need update from redraw?
  2486. if (typeof(svg.opts['forceRedraw']) == 'function') {
  2487. if (svg.opts['forceRedraw']() == true) needUpdate = true;
  2488. }
  2489. // render if needed
  2490. if (needUpdate) {
  2491. draw();
  2492. svg.Mouse.runEvents(); // run and clear our events
  2493. }
  2494. }, 1000 / svg.FRAMERATE);
  2495. }
  2496. svg.stop = function() {
  2497. if (svg.intervalID) {
  2498. clearInterval(svg.intervalID);
  2499. }
  2500. }
  2501. svg.Mouse = new (function() {
  2502. this.events = [];
  2503. this.hasEvents = function() { return this.events.length != 0; }
  2504. this.onclick = function(x, y) {
  2505. this.events.push({ type: 'onclick', x: x, y: y,
  2506. run: function(e) { if (e.onclick) e.onclick(); }
  2507. });
  2508. }
  2509. this.onmousemove = function(x, y) {
  2510. this.events.push({ type: 'onmousemove', x: x, y: y,
  2511. run: function(e) { if (e.onmousemove) e.onmousemove(); }
  2512. });
  2513. }
  2514. this.eventElements = [];
  2515. this.checkPath = function(element, ctx) {
  2516. for (var i=0; i<this.events.length; i++) {
  2517. var e = this.events[i];
  2518. if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;
  2519. }
  2520. }
  2521. this.checkBoundingBox = function(element, bb) {
  2522. for (var i=0; i<this.events.length; i++) {
  2523. var e = this.events[i];
  2524. if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;
  2525. }
  2526. }
  2527. this.runEvents = function() {
  2528. svg.ctx.canvas.style.cursor = '';
  2529. for (var i=0; i<this.events.length; i++) {
  2530. var e = this.events[i];
  2531. var element = this.eventElements[i];
  2532. while (element) {
  2533. e.run(element);
  2534. element = element.parent;
  2535. }
  2536. }
  2537. // done running, clear
  2538. this.events = [];
  2539. this.eventElements = [];
  2540. }
  2541. });
  2542. return svg;
  2543. }
  2544. })();
  2545. if (typeof(CanvasRenderingContext2D) != 'undefined') {
  2546. CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh) {
  2547. canvg(this.canvas, s, {
  2548. ignoreMouse: true,
  2549. ignoreAnimation: true,
  2550. ignoreDimensions: true,
  2551. ignoreClear: true,
  2552. offsetX: dx,
  2553. offsetY: dy,
  2554. scaleWidth: dw,
  2555. scaleHeight: dh
  2556. });
  2557. }
  2558. }