canvg.js 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094
  1. /* eslint-disable */
  2. /*
  3. * canvg.js - Javascript SVG parser and renderer on Canvas
  4. * version 2.0.0
  5. * MIT Licensed
  6. * Gabe Lerner (gabelerner@gmail.com)
  7. * https://github.com/canvg/canvg
  8. *
  9. */
  10. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('rgbcolor'), require('stackblur-canvas')) :
  12. typeof define === 'function' && define.amd ? define(['rgbcolor', 'stackblur-canvas'], factory) :
  13. (global.canvgv2 = factory(global.RGBColor, global.StackBlur));
  14. }(this, (function (rgbcolor, stackblurCanvas) {
  15. 'use strict';
  16. rgbcolor = rgbcolor && rgbcolor.hasOwnProperty('default') ? rgbcolor['default'] : rgbcolor;
  17. stackblurCanvas = stackblurCanvas && stackblurCanvas.hasOwnProperty('default') ? stackblurCanvas['default'] : stackblurCanvas;
  18. function createCommonjsModule(fn, module) {
  19. return module = { exports: {} }, fn(module, module.exports), module.exports;
  20. }
  21. var canvg_1 = createCommonjsModule(function (module) {
  22. /* eslint-env browser, node */
  23. /* globals $, Sizzle, Windows, ActiveXObject */
  24. /* eslint-disable no-redeclare */
  25. var isNode = (module.exports && typeof window === 'undefined'),
  26. nodeEnv = false;
  27. var windowEnv;
  28. {
  29. windowEnv = window;
  30. windowEnv.DOMParser = window.DOMParser;
  31. }
  32. var doc = windowEnv.document,
  33. defaultClientWidth = 800,
  34. defaultClientHeight = 600;
  35. function createCanvas(width, height) {
  36. var c;
  37. {
  38. c = doc.createElement('canvas');
  39. c.width = width;
  40. c.height = height;
  41. }
  42. return c;
  43. }
  44. // canvg(target, s)
  45. // empty parameters: replace all 'svg' elements on page with 'canvas' elements
  46. // target: canvas element or the id of a canvas element
  47. // s: svg string, url to svg file, or xml document
  48. // opts: optional hash of options
  49. // ignoreMouse: true => ignore mouse events
  50. // ignoreAnimation: true => ignore animations
  51. // ignoreDimensions: true => does not try to resize canvas
  52. // ignoreClear: true => does not clear canvas
  53. // offsetX: int => draws at a x offset
  54. // offsetY: int => draws at a y offset
  55. // scaleWidth: int => scales horizontally to width
  56. // scaleHeight: int => scales vertically to height
  57. // renderCallback: function => will call the function after the first render is completed
  58. // enableRedraw: function => whether enable the redraw interval in node environment
  59. // forceRedraw: function => will call the function on every frame, if it returns true, will redraw
  60. var canvg = function (target, s, opts) {
  61. // no parameters
  62. if (target == null && s == null && opts == null) {
  63. var svgTags = doc.querySelectorAll('svg');
  64. for (var i = 0; i < svgTags.length; i++) {
  65. var svgTag = svgTags[i];
  66. var c = doc.createElement('canvas');
  67. if (typeof (svgTag.clientWidth) !== 'undefined' && typeof (svgTag.clientHeight) !== 'undefined') {
  68. c.width = svgTag.clientWidth;
  69. c.height = svgTag.clientHeight;
  70. } else {
  71. var rect = svgTag.getBoundingClientRect();
  72. c.width = rect.width;
  73. c.height = rect.height;
  74. }
  75. svgTag.parentNode.insertBefore(c, svgTag);
  76. svgTag.parentNode.removeChild(svgTag);
  77. var div = doc.createElement('div');
  78. div.appendChild(svgTag);
  79. canvg(c, div.innerHTML);
  80. }
  81. return;
  82. }
  83. var svg = build(opts || {});
  84. if (typeof target == 'string') {
  85. target = doc.getElementById(target);
  86. }
  87. // store class on canvas
  88. if (target.svg != null) target.svg.stop();
  89. // on i.e. 8 for flash canvas, we can't assign the property so check for it
  90. if (!(target.childNodes && target.childNodes.length == 1 && target.childNodes[0].nodeName == 'OBJECT')) target.svg = svg;
  91. var ctx = target.getContext('2d');
  92. if (typeof s.documentElement != 'undefined') {
  93. // load from xml doc
  94. svg.loadXmlDoc(ctx, s);
  95. } else if (s.substr(0, 1) == '<') {
  96. // load from xml string
  97. svg.loadXml(ctx, s);
  98. } else {
  99. // load from url
  100. svg.load(ctx, s);
  101. }
  102. };
  103. var matchesSelector;
  104. {
  105. // see https://developer.mozilla.org/en-US/docs/Web/API/Element.matches
  106. if (typeof Element == 'undefined'); else if (typeof Element.prototype.matches != 'undefined') {
  107. matchesSelector = function (node, selector) {
  108. return node.matches(selector);
  109. };
  110. } else if (typeof Element.prototype.webkitMatchesSelector != 'undefined') {
  111. matchesSelector = function (node, selector) {
  112. return node.webkitMatchesSelector(selector);
  113. };
  114. } else if (typeof Element.prototype.mozMatchesSelector != 'undefined') {
  115. matchesSelector = function (node, selector) {
  116. return node.mozMatchesSelector(selector);
  117. };
  118. } else if (typeof Element.prototype.msMatchesSelector != 'undefined') {
  119. matchesSelector = function (node, selector) {
  120. return node.msMatchesSelector(selector);
  121. };
  122. } else if (typeof Element.prototype.oMatchesSelector != 'undefined') {
  123. matchesSelector = function (node, selector) {
  124. return node.oMatchesSelector(selector);
  125. };
  126. } else {
  127. // requires Sizzle: https://github.com/jquery/sizzle/wiki/Sizzle-Documentation
  128. // or jQuery: http://jquery.com/download/
  129. // or Zepto: http://zeptojs.com/#
  130. // without it, this is a ReferenceError
  131. if (typeof jQuery === 'function' || typeof Zepto === 'function') {
  132. matchesSelector = function (node, selector) {
  133. return $(node).is(selector);
  134. };
  135. }
  136. if (typeof matchesSelector === 'undefined' && typeof Sizzle !== 'undefined') {
  137. matchesSelector = Sizzle.matchesSelector;
  138. }
  139. }
  140. }
  141. // slightly modified version of https://github.com/keeganstreet/specificity/blob/master/specificity.js
  142. var attributeRegex = /(\[[^\]]+\])/g;
  143. var idRegex = /(#[^\s\+>~\.\[:]+)/g;
  144. var classRegex = /(\.[^\s\+>~\.\[:]+)/g;
  145. var pseudoElementRegex = /(::[^\s\+>~\.\[:]+|:first-line|:first-letter|:before|:after)/gi;
  146. var pseudoClassWithBracketsRegex = /(:[\w-]+\([^\)]*\))/gi;
  147. var pseudoClassRegex = /(:[^\s\+>~\.\[:]+)/g;
  148. var elementRegex = /([^\s\+>~\.\[:]+)/g;
  149. function getSelectorSpecificity(selector) {
  150. var typeCount = [0, 0, 0];
  151. var findMatch = function (regex, type) {
  152. var matches = selector.match(regex);
  153. if (matches == null) {
  154. return;
  155. }
  156. typeCount[type] += matches.length;
  157. selector = selector.replace(regex, ' ');
  158. };
  159. selector = selector.replace(/:not\(([^\)]*)\)/g, ' $1 ');
  160. selector = selector.replace(/{[\s\S]*/gm, ' ');
  161. findMatch(attributeRegex, 1);
  162. findMatch(idRegex, 0);
  163. findMatch(classRegex, 1);
  164. findMatch(pseudoElementRegex, 2);
  165. findMatch(pseudoClassWithBracketsRegex, 1);
  166. findMatch(pseudoClassRegex, 1);
  167. selector = selector.replace(/[\*\s\+>~]/g, ' ');
  168. selector = selector.replace(/[#\.]/g, ' ');
  169. findMatch(elementRegex, 2);
  170. return typeCount.join('');
  171. }
  172. function build(opts) {
  173. var svg = { opts: opts };
  174. svg.FRAMERATE = 30;
  175. svg.MAX_VIRTUAL_PIXELS = 30000;
  176. svg.rootEmSize = 12;
  177. svg.emSize = 12;
  178. svg.log = function (/* msg */) { };
  179. if (svg.opts['log'] == true && typeof console != 'undefined') {
  180. svg.log = function (msg) { console.log(msg); }; // eslint-disable-line no-console
  181. }
  182. // globals
  183. svg.init = function (ctx) {
  184. var uniqueId = 0;
  185. svg.UniqueId = function () { uniqueId++; return 'canvg' + uniqueId; };
  186. svg.Definitions = {};
  187. svg.Styles = {};
  188. svg.StylesSpecificity = {};
  189. svg.Animations = [];
  190. svg.Images = [];
  191. svg.ctx = ctx;
  192. svg.ViewPort = new (function () {
  193. this.viewPorts = [];
  194. this.Clear = function () { this.viewPorts = []; };
  195. this.SetCurrent = function (width, height) { this.viewPorts.push({ width: width, height: height }); };
  196. this.RemoveCurrent = function () { this.viewPorts.pop(); };
  197. this.Current = function () { return this.viewPorts[this.viewPorts.length - 1]; };
  198. this.width = function () { return this.Current().width; };
  199. this.height = function () { return this.Current().height; };
  200. this.ComputeSize = function (d) {
  201. if (d != null && typeof d == 'number') return d;
  202. if (d == 'x') return this.width();
  203. if (d == 'y') return this.height();
  204. return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2);
  205. };
  206. });
  207. };
  208. svg.init();
  209. // images loaded
  210. svg.ImagesLoaded = function () {
  211. for (var i = 0; i < svg.Images.length; i++) {
  212. if (!svg.Images[i].loaded) return false;
  213. }
  214. return true;
  215. };
  216. // trim
  217. svg.trim = function (s) { return s.replace(/^\s+|\s+$/g, ''); };
  218. // compress non-ideographic spaces
  219. svg.compressSpaces = function (s) { return s.replace(/(?!\u3000)\s+/gm, ' '); };
  220. // ajax
  221. svg.ajax = function (url) {
  222. var AJAX;
  223. if (windowEnv.XMLHttpRequest) { AJAX = new windowEnv.XMLHttpRequest(); } else { AJAX = new ActiveXObject('Microsoft.XMLHTTP'); }
  224. if (AJAX) {
  225. AJAX.open('GET', url, false);
  226. AJAX.send(null);
  227. return AJAX.responseText;
  228. }
  229. return null;
  230. };
  231. // parse xml
  232. svg.parseXml = function (xml) {
  233. if (typeof Windows != 'undefined' && typeof Windows.Data != 'undefined' && typeof Windows.Data.Xml != 'undefined') {
  234. var xmlDoc = new Windows.Data.Xml.Dom.XmlDocument();
  235. var settings = new Windows.Data.Xml.Dom.XmlLoadSettings();
  236. settings.prohibitDtd = false;
  237. xmlDoc.loadXml(xml, settings);
  238. return xmlDoc;
  239. } else if (windowEnv.DOMParser) {
  240. try {
  241. var parser = opts.xmldom ? new windowEnv.DOMParser(opts.xmldom) : new windowEnv.DOMParser();
  242. return parser.parseFromString(xml, 'image/svg+xml');
  243. } catch (e) {
  244. parser = opts.xmldom ? new windowEnv.DOMParser(opts.xmldom) : new windowEnv.DOMParser();
  245. return parser.parseFromString(xml, 'text/xml');
  246. }
  247. } else {
  248. xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
  249. var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
  250. xmlDoc.async = 'false';
  251. xmlDoc.loadXML(xml);
  252. return xmlDoc;
  253. }
  254. };
  255. svg.Property = function (name, value) {
  256. this.name = name;
  257. this.value = value;
  258. };
  259. svg.Property.prototype.getValue = function () {
  260. return this.value;
  261. };
  262. svg.Property.prototype.hasValue = function () {
  263. return (this.value != null && this.value !== '');
  264. };
  265. // return the numerical value of the property
  266. svg.Property.prototype.numValue = function () {
  267. if (!this.hasValue()) return 0;
  268. var n = parseFloat(this.value);
  269. if ((this.value + '').match(/%$/)) {
  270. n = n / 100.0;
  271. }
  272. return n;
  273. };
  274. svg.Property.prototype.valueOrDefault = function (def) {
  275. if (this.hasValue()) return this.value;
  276. return def;
  277. };
  278. svg.Property.prototype.numValueOrDefault = function (def) {
  279. if (this.hasValue()) return this.numValue();
  280. return parseFloat(def);
  281. };
  282. // color extensions
  283. // augment the current color value with the opacity
  284. svg.Property.prototype.addOpacity = function (opacityProp) {
  285. var newValue = this.value;
  286. if (opacityProp.value != null && opacityProp.value != '' && typeof this.value == 'string') { // can only add opacity to colors, not patterns
  287. var color = new rgbcolor(this.value);
  288. if (color.ok) {
  289. newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacityProp.numValue() + ')';
  290. }
  291. }
  292. return new svg.Property(this.name, newValue);
  293. };
  294. // definition extensions
  295. // get the definition from the definitions table
  296. svg.Property.prototype.getDefinition = function () {
  297. var name = this.value.match(/#([^\)'"]+)/);
  298. if (name) { name = name[1]; }
  299. if (!name) { name = this.value; }
  300. return svg.Definitions[name];
  301. };
  302. svg.Property.prototype.isUrlDefinition = function () {
  303. return this.value.indexOf('url(') == 0
  304. };
  305. svg.Property.prototype.getFillStyleDefinition = function (e, opacityProp) {
  306. var def = this.getDefinition();
  307. // gradient
  308. if (def != null && def.createGradient) {
  309. return def.createGradient(svg.ctx, e, opacityProp);
  310. }
  311. // pattern
  312. if (def != null && def.createPattern) {
  313. if (def.getHrefAttribute().hasValue()) {
  314. var pt = def.attribute('patternTransform');
  315. def = def.getHrefAttribute().getDefinition();
  316. if (pt.hasValue()) { def.attribute('patternTransform', true).value = pt.value; }
  317. }
  318. return def.createPattern(svg.ctx, e, opacityProp);
  319. }
  320. return null;
  321. };
  322. // length extensions
  323. svg.Property.prototype.getDPI = function (/* viewPort */) {
  324. return 96.0; // TODO: compute?
  325. };
  326. svg.Property.prototype.getREM = function (/* viewPort */) {
  327. return svg.rootEmSize;
  328. };
  329. svg.Property.prototype.getEM = function (/* viewPort */) {
  330. return svg.emSize;
  331. };
  332. svg.Property.prototype.getUnits = function () {
  333. var s = this.value + '';
  334. return s.replace(/[0-9\.\-]/g, '');
  335. };
  336. svg.Property.prototype.isPixels = function () {
  337. if (!this.hasValue()) return false;
  338. var s = this.value + '';
  339. if (s.match(/px$/)) return true;
  340. if (s.match(/^[0-9]+$/)) return true;
  341. return false;
  342. };
  343. // get the length as pixels
  344. svg.Property.prototype.toPixels = function (viewPort, processPercent) {
  345. if (!this.hasValue()) return 0;
  346. var s = this.value + '';
  347. if (s.match(/rem$/)) return this.numValue() * this.getREM(viewPort);
  348. if (s.match(/em$/)) return this.numValue() * this.getEM(viewPort);
  349. if (s.match(/ex$/)) return this.numValue() * this.getEM(viewPort) / 2.0;
  350. if (s.match(/px$/)) return this.numValue();
  351. if (s.match(/pt$/)) return this.numValue() * this.getDPI(viewPort) * (1.0 / 72.0);
  352. if (s.match(/pc$/)) return this.numValue() * 15;
  353. if (s.match(/cm$/)) return this.numValue() * this.getDPI(viewPort) / 2.54;
  354. if (s.match(/mm$/)) return this.numValue() * this.getDPI(viewPort) / 25.4;
  355. if (s.match(/in$/)) return this.numValue() * this.getDPI(viewPort);
  356. if (s.match(/%$/)) return this.numValue() * svg.ViewPort.ComputeSize(viewPort);
  357. var n = this.numValue();
  358. if (processPercent && n < 1.0) return n * svg.ViewPort.ComputeSize(viewPort);
  359. return n;
  360. };
  361. // time extensions
  362. // get the time as milliseconds
  363. // https://svgwg.org/specs/animations/#ClockValueSyntax
  364. svg.Property.prototype.toMilliseconds = function () {
  365. if (!this.hasValue()) return 0;
  366. var s = this.value + '';
  367. if (s.match(/ms$/)) return this.numValue();
  368. return this.numValue() * 1000;
  369. };
  370. // angle extensions
  371. // get the angle as radians
  372. svg.Property.prototype.toRadians = function () {
  373. if (!this.hasValue()) return 0;
  374. var s = this.value + '';
  375. if (s.match(/deg$/)) return this.numValue() * (Math.PI / 180.0);
  376. if (s.match(/grad$/)) return this.numValue() * (Math.PI / 200.0);
  377. if (s.match(/rad$/)) return this.numValue();
  378. return this.numValue() * (Math.PI / 180.0);
  379. };
  380. // text extensions
  381. // get the text baseline
  382. var textBaselineMapping = {
  383. 'baseline': 'alphabetic',
  384. 'before-edge': 'top',
  385. 'text-before-edge': 'top',
  386. 'middle': 'middle',
  387. 'central': 'middle',
  388. 'after-edge': 'bottom',
  389. 'text-after-edge': 'bottom',
  390. 'ideographic': 'ideographic',
  391. 'alphabetic': 'alphabetic',
  392. 'hanging': 'hanging',
  393. 'mathematical': 'alphabetic'
  394. };
  395. svg.Property.prototype.toTextBaseline = function () {
  396. if (!this.hasValue()) return null;
  397. return textBaselineMapping[this.value];
  398. };
  399. // fonts
  400. svg.Font = new (function () {
  401. this.Styles = 'normal|italic|oblique|inherit';
  402. this.Variants = 'normal|small-caps|inherit';
  403. this.Weights = 'normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit';
  404. this.CreateFont = function (fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) {
  405. var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font);
  406. fontFamily = fontFamily || f.fontFamily;
  407. return {
  408. fontFamily: fontFamily,
  409. fontSize: fontSize || f.fontSize,
  410. fontStyle: fontStyle || f.fontStyle,
  411. fontWeight: fontWeight || f.fontWeight,
  412. fontVariant: fontVariant || f.fontVariant,
  413. toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') }
  414. }
  415. };
  416. var that = this;
  417. this.Parse = function (s) {
  418. var f = {};
  419. var d = svg.trim(svg.compressSpaces(s || '')).split(' ');
  420. var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false };
  421. var ff = '';
  422. for (var i = 0; i < d.length; i++) {
  423. if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) {
  424. if (d[i] != 'inherit') f.fontStyle = d[i];
  425. set.fontStyle = true;
  426. } else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) {
  427. if (d[i] != 'inherit') f.fontVariant = d[i];
  428. set.fontStyle = set.fontVariant = true;
  429. } else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) {
  430. if (d[i] != 'inherit') f.fontWeight = d[i];
  431. set.fontStyle = set.fontVariant = set.fontWeight = true;
  432. } else if (!set.fontSize) {
  433. if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0];
  434. set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true;
  435. } else { if (d[i] != 'inherit') ff += d[i]; }
  436. }
  437. if (ff != '') f.fontFamily = ff;
  438. return f;
  439. };
  440. });
  441. // points and paths
  442. svg.ToNumberArray = function (s) {
  443. var a = (s || '').match(/-?(\d+(?:\.\d*(?:[eE][+-]?\d+)?)?|\.\d+)(?=\D|$)/gm) || [];
  444. for (var i = 0; i < a.length; i++) {
  445. a[i] = parseFloat(a[i]);
  446. }
  447. return a;
  448. };
  449. svg.Point = function (x, y) {
  450. this.x = x;
  451. this.y = y;
  452. };
  453. svg.Point.prototype.angleTo = function (p) {
  454. return Math.atan2(p.y - this.y, p.x - this.x);
  455. };
  456. svg.Point.prototype.applyTransform = function (v) {
  457. var xp = this.x * v[0] + this.y * v[2] + v[4];
  458. var yp = this.x * v[1] + this.y * v[3] + v[5];
  459. this.x = xp;
  460. this.y = yp;
  461. };
  462. svg.CreatePoint = function (s) {
  463. var a = svg.ToNumberArray(s);
  464. return new svg.Point(a[0], a[1]);
  465. };
  466. svg.CreatePath = function (s) {
  467. var a = svg.ToNumberArray(s);
  468. var path = [];
  469. for (var i = 0; i < a.length; i += 2) {
  470. path.push(new svg.Point(a[i], a[i + 1]));
  471. }
  472. return path;
  473. };
  474. // bounding box
  475. svg.BoundingBox = function (x1, y1, x2, y2) { // pass in initial points if you want
  476. this.x1 = Number.NaN;
  477. this.y1 = Number.NaN;
  478. this.x2 = Number.NaN;
  479. this.y2 = Number.NaN;
  480. this.x = function () { return this.x1; };
  481. this.y = function () { return this.y1; };
  482. this.width = function () { return this.x2 - this.x1; };
  483. this.height = function () { return this.y2 - this.y1; };
  484. this.addPoint = function (x, y) {
  485. if (x != null) {
  486. if (isNaN(this.x1) || isNaN(this.x2)) {
  487. this.x1 = x;
  488. this.x2 = x;
  489. }
  490. if (x < this.x1) this.x1 = x;
  491. if (x > this.x2) this.x2 = x;
  492. }
  493. if (y != null) {
  494. if (isNaN(this.y1) || isNaN(this.y2)) {
  495. this.y1 = y;
  496. this.y2 = y;
  497. }
  498. if (y < this.y1) this.y1 = y;
  499. if (y > this.y2) this.y2 = y;
  500. }
  501. };
  502. this.addX = function (x) { this.addPoint(x, null); };
  503. this.addY = function (y) { this.addPoint(null, y); };
  504. this.addBoundingBox = function (bb) {
  505. this.addPoint(bb.x1, bb.y1);
  506. this.addPoint(bb.x2, bb.y2);
  507. };
  508. this.addQuadraticCurve = function (p0x, p0y, p1x, p1y, p2x, p2y) {
  509. var cp1x = p0x + 2 / 3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0)
  510. var cp1y = p0y + 2 / 3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0)
  511. var cp2x = cp1x + 1 / 3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0)
  512. var cp2y = cp1y + 1 / 3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0)
  513. this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y);
  514. };
  515. this.addBezierCurve = function (p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
  516. // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
  517. var p0 = [p0x, p0y],
  518. p1 = [p1x, p1y],
  519. p2 = [p2x, p2y],
  520. p3 = [p3x, p3y];
  521. this.addPoint(p0[0], p0[1]);
  522. this.addPoint(p3[0], p3[1]);
  523. for (var i = 0; i <= 1; i++) {
  524. var f = function (t) {
  525. return Math.pow(1 - t, 3) * p0[i] +
  526. 3 * Math.pow(1 - t, 2) * t * p1[i] +
  527. 3 * (1 - t) * Math.pow(t, 2) * p2[i] +
  528. Math.pow(t, 3) * p3[i];
  529. };
  530. var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
  531. var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
  532. var c = 3 * p1[i] - 3 * p0[i];
  533. if (a == 0) {
  534. if (b == 0) continue;
  535. var t = -c / b;
  536. if (0 < t && t < 1) {
  537. if (i == 0) this.addX(f(t));
  538. if (i == 1) this.addY(f(t));
  539. }
  540. continue;
  541. }
  542. var b2ac = Math.pow(b, 2) - 4 * c * a;
  543. if (b2ac < 0) continue;
  544. var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
  545. if (0 < t1 && t1 < 1) {
  546. if (i == 0) this.addX(f(t1));
  547. if (i == 1) this.addY(f(t1));
  548. }
  549. var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
  550. if (0 < t2 && t2 < 1) {
  551. if (i == 0) this.addX(f(t2));
  552. if (i == 1) this.addY(f(t2));
  553. }
  554. }
  555. };
  556. this.isPointInBox = function (x, y) {
  557. return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2);
  558. };
  559. this.addPoint(x1, y1);
  560. this.addPoint(x2, y2);
  561. };
  562. // transforms
  563. svg.Transform = function (v) {
  564. var that = this;
  565. this.Type = {};
  566. // translate
  567. this.Type.translate = function (s) {
  568. this.p = svg.CreatePoint(s);
  569. this.apply = function (ctx) {
  570. ctx.translate(this.p.x || 0.0, this.p.y || 0.0);
  571. };
  572. this.unapply = function (ctx) {
  573. ctx.translate(-1.0 * this.p.x || 0.0, -1.0 * this.p.y || 0.0);
  574. };
  575. this.applyToPoint = function (p) {
  576. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  577. };
  578. };
  579. // rotate
  580. this.Type.rotate = function (s) {
  581. var a = svg.ToNumberArray(s);
  582. this.angle = new svg.Property('angle', a[0]);
  583. this.cx = a[1] || 0;
  584. this.cy = a[2] || 0;
  585. this.apply = function (ctx) {
  586. ctx.translate(this.cx, this.cy);
  587. ctx.rotate(this.angle.toRadians());
  588. ctx.translate(-this.cx, -this.cy);
  589. };
  590. this.unapply = function (ctx) {
  591. ctx.translate(this.cx, this.cy);
  592. ctx.rotate(-1.0 * this.angle.toRadians());
  593. ctx.translate(-this.cx, -this.cy);
  594. };
  595. this.applyToPoint = function (p) {
  596. var a = this.angle.toRadians();
  597. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  598. p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]);
  599. p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]);
  600. };
  601. };
  602. this.Type.scale = function (s) {
  603. this.p = svg.CreatePoint(s);
  604. this.apply = function (ctx) {
  605. ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0);
  606. };
  607. this.unapply = function (ctx) {
  608. ctx.scale(1.0 / this.p.x || 1.0, 1.0 / this.p.y || this.p.x || 1.0);
  609. };
  610. this.applyToPoint = function (p) {
  611. p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]);
  612. };
  613. };
  614. this.Type.matrix = function (s) {
  615. this.m = svg.ToNumberArray(s);
  616. this.apply = function (ctx) {
  617. ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
  618. };
  619. this.unapply = function (ctx) {
  620. var a = this.m[0];
  621. var b = this.m[2];
  622. var c = this.m[4];
  623. var d = this.m[1];
  624. var e = this.m[3];
  625. var f = this.m[5];
  626. var g = 0.0;
  627. var h = 0.0;
  628. var i = 1.0;
  629. var det = 1 / (a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g));
  630. ctx.transform(
  631. det * (e * i - f * h),
  632. det * (f * g - d * i),
  633. det * (c * h - b * i),
  634. det * (a * i - c * g),
  635. det * (b * f - c * e),
  636. det * (c * d - a * f)
  637. );
  638. };
  639. this.applyToPoint = function (p) {
  640. p.applyTransform(this.m);
  641. };
  642. };
  643. this.Type.SkewBase = function (s) {
  644. this.base = that.Type.matrix;
  645. this.base(s);
  646. this.angle = new svg.Property('angle', s);
  647. };
  648. this.Type.SkewBase.prototype = new this.Type.matrix;
  649. this.Type.skewX = function (s) {
  650. this.base = that.Type.SkewBase;
  651. this.base(s);
  652. this.m = [1, 0, Math.tan(this.angle.toRadians()), 1, 0, 0];
  653. };
  654. this.Type.skewX.prototype = new this.Type.SkewBase;
  655. this.Type.skewY = function (s) {
  656. this.base = that.Type.SkewBase;
  657. this.base(s);
  658. this.m = [1, Math.tan(this.angle.toRadians()), 0, 1, 0, 0];
  659. };
  660. this.Type.skewY.prototype = new this.Type.SkewBase;
  661. this.transforms = [];
  662. this.apply = function (ctx) {
  663. for (var i = 0; i < this.transforms.length; i++) {
  664. this.transforms[i].apply(ctx);
  665. }
  666. };
  667. this.unapply = function (ctx) {
  668. for (var i = this.transforms.length - 1; i >= 0; i--) {
  669. this.transforms[i].unapply(ctx);
  670. }
  671. };
  672. // TODO: applyToPoint unused ... remove?
  673. this.applyToPoint = function (p) {
  674. for (var i = 0; i < this.transforms.length; i++) {
  675. this.transforms[i].applyToPoint(p);
  676. }
  677. };
  678. var data = svg.trim(svg.compressSpaces(v)).replace(/\)([a-zA-Z])/g, ') $1').replace(/\)(\s?,\s?)/g, ') ').split(/\s(?=[a-z])/);
  679. for (var i = 0; i < data.length; i++) {
  680. if (data[i] === 'none') {
  681. continue;
  682. }
  683. var type = svg.trim(data[i].split('(')[0]);
  684. var s = data[i].split('(')[1].replace(')', '');
  685. var transformType = this.Type[type];
  686. if (typeof transformType != 'undefined') {
  687. var transform = new transformType(s);
  688. transform.type = type;
  689. this.transforms.push(transform);
  690. }
  691. }
  692. };
  693. // aspect ratio
  694. svg.AspectRatio = function (ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {
  695. // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
  696. aspectRatio = svg.compressSpaces(aspectRatio);
  697. aspectRatio = aspectRatio.replace(/^defer\s/, ''); // ignore defer
  698. var align = aspectRatio.split(' ')[0] || 'xMidYMid';
  699. var meetOrSlice = aspectRatio.split(' ')[1] || 'meet';
  700. // calculate scale
  701. var scaleX = width / desiredWidth;
  702. var scaleY = height / desiredHeight;
  703. var scaleMin = Math.min(scaleX, scaleY);
  704. var scaleMax = Math.max(scaleX, scaleY);
  705. if (meetOrSlice == 'meet') {
  706. desiredWidth *= scaleMin;
  707. desiredHeight *= scaleMin;
  708. }
  709. if (meetOrSlice == 'slice') {
  710. desiredWidth *= scaleMax;
  711. desiredHeight *= scaleMax;
  712. }
  713. refX = new svg.Property('refX', refX);
  714. refY = new svg.Property('refY', refY);
  715. if (refX.hasValue() && refY.hasValue()) {
  716. ctx.translate(-scaleMin * refX.toPixels('x'), -scaleMin * refY.toPixels('y'));
  717. } else {
  718. // align
  719. if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);
  720. if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);
  721. if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0);
  722. if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight);
  723. }
  724. // scale
  725. if (align == 'none') ctx.scale(scaleX, scaleY);
  726. else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin);
  727. else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax);
  728. // translate
  729. ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);
  730. };
  731. // elements
  732. svg.Element = {};
  733. svg.EmptyProperty = new svg.Property('EMPTY', '');
  734. svg.Element.ElementBase = function (node) {
  735. this.attributes = {};
  736. this.styles = {};
  737. this.stylesSpecificity = {};
  738. this.children = [];
  739. // get or create attribute
  740. this.attribute = function (name, createIfNotExists) {
  741. var a = this.attributes[name];
  742. if (a != null) return a;
  743. if (createIfNotExists == true) {
  744. a = new svg.Property(name, '');
  745. this.attributes[name] = a;
  746. }
  747. return a || svg.EmptyProperty;
  748. };
  749. this.getHrefAttribute = function () {
  750. for (var a in this.attributes) {
  751. if (a == 'href' || a.match(/:href$/)) {
  752. return this.attributes[a];
  753. }
  754. }
  755. return svg.EmptyProperty;
  756. };
  757. // get or create style, crawls up node tree
  758. this.style = function (name, createIfNotExists, skipAncestors) {
  759. var s = this.styles[name];
  760. if (s != null) return s;
  761. var a = this.attribute(name);
  762. if (a != null && a.hasValue()) {
  763. this.styles[name] = a; // move up to me to cache
  764. return a;
  765. }
  766. if (skipAncestors != true) {
  767. var p = this.parent;
  768. if (p != null) {
  769. var ps = p.style(name);
  770. if (ps != null && ps.hasValue()) {
  771. return ps;
  772. }
  773. }
  774. }
  775. if (createIfNotExists == true) {
  776. s = new svg.Property(name, '');
  777. this.styles[name] = s;
  778. }
  779. return s || svg.EmptyProperty;
  780. };
  781. // base render
  782. this.render = function (ctx) {
  783. // don't render display=none
  784. if (this.style('display').value == 'none') return;
  785. // don't render visibility=hidden
  786. if (this.style('visibility').value == 'hidden') return;
  787. ctx.save();
  788. if (this.style('mask').hasValue()) { // mask
  789. var mask = this.style('mask').getDefinition();
  790. if (mask != null) mask.apply(ctx, this);
  791. } else if (this.style('filter').hasValue()) { // filter
  792. var filter = this.style('filter').getDefinition();
  793. if (filter != null) filter.apply(ctx, this);
  794. } else {
  795. this.setContext(ctx);
  796. this.renderChildren(ctx);
  797. this.clearContext(ctx);
  798. }
  799. ctx.restore();
  800. };
  801. // base set context
  802. this.setContext = function (/* ctx */) {
  803. // OVERRIDE ME!
  804. };
  805. // base clear context
  806. this.clearContext = function (/* ctx */) {
  807. // OVERRIDE ME!
  808. };
  809. // base render children
  810. this.renderChildren = function (ctx) {
  811. for (var i = 0; i < this.children.length; i++) {
  812. this.children[i].render(ctx);
  813. }
  814. };
  815. this.addChild = function (childNode, create) {
  816. var child = childNode;
  817. if (create) child = svg.CreateElement(childNode);
  818. child.parent = this;
  819. if (child.type != 'title') { this.children.push(child); }
  820. };
  821. this.addStylesFromStyleDefinition = function () {
  822. // add styles
  823. for (var selector in svg.Styles) {
  824. if (selector[0] != '@' && matchesSelector(node, selector)) {
  825. var styles = svg.Styles[selector];
  826. var specificity = svg.StylesSpecificity[selector];
  827. if (styles != null) {
  828. for (var name in styles) {
  829. var existingSpecificity = this.stylesSpecificity[name];
  830. if (typeof existingSpecificity == 'undefined') {
  831. existingSpecificity = '000';
  832. }
  833. if (specificity >= existingSpecificity) {
  834. this.styles[name] = styles[name];
  835. this.stylesSpecificity[name] = specificity;
  836. }
  837. }
  838. }
  839. }
  840. }
  841. };
  842. // Microsoft Edge fix
  843. var allUppercase = new RegExp('^[A-Z\-]+$');
  844. var normalizeAttributeName = function (name) {
  845. if (allUppercase.test(name)) {
  846. return name.toLowerCase();
  847. }
  848. return name;
  849. };
  850. if (node != null && node.nodeType == 1) { //ELEMENT_NODE
  851. // add attributes
  852. for (var i = 0; i < node.attributes.length; i++) {
  853. var attribute = node.attributes[i];
  854. var nodeName = normalizeAttributeName(attribute.nodeName);
  855. this.attributes[nodeName] = new svg.Property(nodeName, attribute.value);
  856. }
  857. this.addStylesFromStyleDefinition();
  858. // add inline styles
  859. if (this.attribute('style').hasValue()) {
  860. var styles = this.attribute('style').value.split(';');
  861. for (var i = 0; i < styles.length; i++) {
  862. if (svg.trim(styles[i]) != '') {
  863. var style = styles[i].split(':');
  864. var name = svg.trim(style[0]);
  865. var value = svg.trim(style[1]);
  866. this.styles[name] = new svg.Property(name, value);
  867. }
  868. }
  869. }
  870. // add id
  871. if (this.attribute('id').hasValue()) {
  872. if (svg.Definitions[this.attribute('id').value] == null) {
  873. svg.Definitions[this.attribute('id').value] = this;
  874. }
  875. }
  876. // add children
  877. for (var i = 0; i < node.childNodes.length; i++) {
  878. var childNode = node.childNodes[i];
  879. if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE
  880. if (this.captureTextNodes && (childNode.nodeType == 3 || childNode.nodeType == 4)) {
  881. var text = childNode.value || childNode.text || childNode.textContent || '';
  882. if (svg.compressSpaces(text) != '') {
  883. this.addChild(new svg.Element.tspan(childNode), false); // TEXT_NODE
  884. }
  885. }
  886. }
  887. }
  888. };
  889. svg.Element.RenderedElementBase = function (node) {
  890. this.base = svg.Element.ElementBase;
  891. this.base(node);
  892. this.calculateOpacity = function () {
  893. var opacity = 1.0;
  894. var el = this;
  895. while (el != null) {
  896. var opacityStyle = el.style('opacity', false, true); // no ancestors on style call
  897. if (opacityStyle.hasValue()) {
  898. opacity = opacity * opacityStyle.numValue();
  899. }
  900. el = el.parent;
  901. }
  902. return opacity;
  903. };
  904. this.setContext = function (ctx, fromMeasure) {
  905. if (!fromMeasure) { // causes stack overflow when measuring text with gradients
  906. // fill
  907. if (this.style('fill').isUrlDefinition()) {
  908. var fs = this.style('fill').getFillStyleDefinition(this, this.style('fill-opacity'));
  909. if (fs != null) ctx.fillStyle = fs;
  910. } else if (this.style('fill').hasValue()) {
  911. var fillStyle = this.style('fill');
  912. if (fillStyle.value == 'currentColor') fillStyle.value = this.style('color').value;
  913. if (fillStyle.value != 'inherit') ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);
  914. }
  915. if (this.style('fill-opacity').hasValue()) {
  916. var fillStyle = new svg.Property('fill', ctx.fillStyle);
  917. fillStyle = fillStyle.addOpacity(this.style('fill-opacity'));
  918. ctx.fillStyle = fillStyle.value;
  919. }
  920. // stroke
  921. if (this.style('stroke').isUrlDefinition()) {
  922. var fs = this.style('stroke').getFillStyleDefinition(this, this.style('stroke-opacity'));
  923. if (fs != null) ctx.strokeStyle = fs;
  924. } else if (this.style('stroke').hasValue()) {
  925. var strokeStyle = this.style('stroke');
  926. if (strokeStyle.value == 'currentColor') strokeStyle.value = this.style('color').value;
  927. if (strokeStyle.value != 'inherit') ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);
  928. }
  929. if (this.style('stroke-opacity').hasValue()) {
  930. var strokeStyle = new svg.Property('stroke', ctx.strokeStyle);
  931. strokeStyle = strokeStyle.addOpacity(this.style('stroke-opacity'));
  932. ctx.strokeStyle = strokeStyle.value;
  933. }
  934. if (this.style('stroke-width').hasValue()) {
  935. var newLineWidth = this.style('stroke-width').toPixels();
  936. ctx.lineWidth = newLineWidth == 0 ? 0.001 : newLineWidth; // browsers don't respect 0
  937. }
  938. if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;
  939. if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;
  940. if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;
  941. if (this.style('paint-order').hasValue()) ctx.paintOrder = this.style('paint-order').value;
  942. if (this.style('stroke-dasharray').hasValue() && this.style('stroke-dasharray').value != 'none') {
  943. var gaps = svg.ToNumberArray(this.style('stroke-dasharray').value);
  944. if (typeof ctx.setLineDash != 'undefined') { ctx.setLineDash(gaps); } else if (typeof ctx.webkitLineDash != 'undefined') { ctx.webkitLineDash = gaps; } else if (typeof ctx.mozDash != 'undefined' && !(gaps.length == 1 && gaps[0] == 0)) { ctx.mozDash = gaps; }
  945. var offset = this.style('stroke-dashoffset').toPixels();
  946. if (typeof ctx.lineDashOffset != 'undefined') { ctx.lineDashOffset = offset; } else if (typeof ctx.webkitLineDashOffset != 'undefined') { ctx.webkitLineDashOffset = offset; } else if (typeof ctx.mozDashOffset != 'undefined') { ctx.mozDashOffset = offset; }
  947. }
  948. }
  949. // font
  950. if (typeof ctx.font != 'undefined') {
  951. if (this.style('font').hasValue()) {
  952. ctx.font = this.style('font').value;
  953. } else {
  954. ctx.font = svg.Font.CreateFont(
  955. this.style('font-style').value,
  956. this.style('font-variant').value,
  957. this.style('font-weight').value,
  958. this.style('font-size').hasValue() ? this.style('font-size').toPixels() + 'px' : '',
  959. this.style('font-family').value).toString();
  960. // update em size if needed
  961. var currentFontSize = this.style('font-size', false, false);
  962. if (currentFontSize.isPixels()) {
  963. svg.emSize = currentFontSize.toPixels();
  964. }
  965. }
  966. }
  967. // transform
  968. if (this.style('transform', false, true).hasValue()) {
  969. var transform = new svg.Transform(this.style('transform', false, true).value);
  970. transform.apply(ctx);
  971. }
  972. // clip
  973. if (this.style('clip-path', false, true).hasValue()) {
  974. var clip = this.style('clip-path', false, true).getDefinition();
  975. if (clip != null) clip.apply(ctx);
  976. }
  977. // opacity
  978. ctx.globalAlpha = this.calculateOpacity();
  979. };
  980. };
  981. svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase;
  982. svg.Element.PathElementBase = function (node) {
  983. this.base = svg.Element.RenderedElementBase;
  984. this.base(node);
  985. this.path = function (ctx) {
  986. if (ctx != null) ctx.beginPath();
  987. return new svg.BoundingBox();
  988. };
  989. this.renderChildren = function (ctx) {
  990. this.path(ctx);
  991. svg.Mouse.checkPath(this, ctx);
  992. if (ctx.fillStyle != '') {
  993. if (this.style('fill-rule').valueOrDefault('inherit') != 'inherit') { ctx.fill(this.style('fill-rule').value); } else { ctx.fill(); }
  994. }
  995. if (ctx.strokeStyle != '') ctx.stroke();
  996. var markers = this.getMarkers();
  997. if (markers != null) {
  998. if (this.style('marker-start').isUrlDefinition()) {
  999. var marker = this.style('marker-start').getDefinition();
  1000. marker.render(ctx, markers[0][0], markers[0][1]);
  1001. }
  1002. if (this.style('marker-mid').isUrlDefinition()) {
  1003. var marker = this.style('marker-mid').getDefinition();
  1004. for (var i = 1; i < markers.length - 1; i++) {
  1005. marker.render(ctx, markers[i][0], markers[i][1]);
  1006. }
  1007. }
  1008. if (this.style('marker-end').isUrlDefinition()) {
  1009. var marker = this.style('marker-end').getDefinition();
  1010. marker.render(ctx, markers[markers.length - 1][0], markers[markers.length - 1][1]);
  1011. }
  1012. }
  1013. };
  1014. this.getBoundingBox = function () {
  1015. return this.path();
  1016. };
  1017. this.getMarkers = function () {
  1018. return null;
  1019. };
  1020. };
  1021. svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase;
  1022. svg.SetDefaults = function (ctx) {
  1023. // initial values and defaults
  1024. ctx.strokeStyle = 'rgba(0,0,0,0)';
  1025. ctx.lineCap = 'butt';
  1026. ctx.lineJoin = 'miter';
  1027. ctx.miterLimit = 4;
  1028. };
  1029. // svg element
  1030. svg.Element.svg = function (node) {
  1031. this.base = svg.Element.RenderedElementBase;
  1032. this.base(node);
  1033. this.baseClearContext = this.clearContext;
  1034. this.clearContext = function (ctx) {
  1035. this.baseClearContext(ctx);
  1036. svg.ViewPort.RemoveCurrent();
  1037. };
  1038. this.baseSetContext = this.setContext;
  1039. this.setContext = function (ctx) {
  1040. svg.SetDefaults(ctx);
  1041. if (ctx.canvas.style && typeof ctx.font != 'undefined' && typeof windowEnv.getComputedStyle != 'undefined') {
  1042. ctx.font = windowEnv.getComputedStyle(ctx.canvas).getPropertyValue('font');
  1043. var fontSize = new svg.Property('fontSize', svg.Font.Parse(ctx.font).fontSize);
  1044. if (fontSize.hasValue()) svg.rootEmSize = svg.emSize = fontSize.toPixels('y');
  1045. }
  1046. this.baseSetContext(ctx);
  1047. // create new view port
  1048. if (!this.attribute('x').hasValue()) this.attribute('x', true).value = 0;
  1049. if (!this.attribute('y').hasValue()) this.attribute('y', true).value = 0;
  1050. ctx.translate(this.attribute('x').toPixels('x'), this.attribute('y').toPixels('y'));
  1051. var width = svg.ViewPort.width();
  1052. var height = svg.ViewPort.height();
  1053. if (!this.attribute('width').hasValue()) this.attribute('width', true).value = '100%';
  1054. if (!this.attribute('height').hasValue()) this.attribute('height', true).value = '100%';
  1055. if (typeof this.root == 'undefined') {
  1056. width = this.attribute('width').toPixels('x');
  1057. height = this.attribute('height').toPixels('y');
  1058. var x = 0;
  1059. var y = 0;
  1060. if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {
  1061. x = -this.attribute('refX').toPixels('x');
  1062. y = -this.attribute('refY').toPixels('y');
  1063. }
  1064. if (this.attribute('overflow').valueOrDefault('hidden') != 'visible') {
  1065. ctx.beginPath();
  1066. ctx.moveTo(x, y);
  1067. ctx.lineTo(width, y);
  1068. ctx.lineTo(width, height);
  1069. ctx.lineTo(x, height);
  1070. ctx.closePath();
  1071. ctx.clip();
  1072. }
  1073. }
  1074. svg.ViewPort.SetCurrent(width, height);
  1075. // viewbox
  1076. if (this.attribute('viewBox').hasValue()) {
  1077. var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
  1078. var minX = viewBox[0];
  1079. var minY = viewBox[1];
  1080. width = viewBox[2];
  1081. height = viewBox[3];
  1082. svg.AspectRatio(ctx,
  1083. this.attribute('preserveAspectRatio').value,
  1084. svg.ViewPort.width(),
  1085. width,
  1086. svg.ViewPort.height(),
  1087. height,
  1088. minX,
  1089. minY,
  1090. this.attribute('refX').value,
  1091. this.attribute('refY').value);
  1092. svg.ViewPort.RemoveCurrent();
  1093. svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
  1094. }
  1095. };
  1096. };
  1097. svg.Element.svg.prototype = new svg.Element.RenderedElementBase;
  1098. // rect element
  1099. svg.Element.rect = function (node) {
  1100. this.base = svg.Element.PathElementBase;
  1101. this.base(node);
  1102. this.path = function (ctx) {
  1103. var x = this.attribute('x').toPixels('x');
  1104. var y = this.attribute('y').toPixels('y');
  1105. var width = this.attribute('width').toPixels('x');
  1106. var height = this.attribute('height').toPixels('y');
  1107. var rx = this.attribute('rx').toPixels('x');
  1108. var ry = this.attribute('ry').toPixels('y');
  1109. if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;
  1110. if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;
  1111. rx = Math.min(rx, width / 2.0);
  1112. ry = Math.min(ry, height / 2.0);
  1113. if (ctx != null) {
  1114. var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
  1115. ctx.beginPath(); // always start the path so we don't fill prior paths
  1116. if (height > 0 && width > 0) {
  1117. ctx.moveTo(x + rx, y);
  1118. ctx.lineTo(x + width - rx, y);
  1119. ctx.bezierCurveTo(x + width - rx + (KAPPA * rx), y, x + width, y + ry - (KAPPA * ry), x + width, y + ry);
  1120. ctx.lineTo(x + width, y + height - ry);
  1121. ctx.bezierCurveTo(x + width, y + height - ry + (KAPPA * ry), x + width - rx + (KAPPA * rx), y + height, x + width - rx, y + height);
  1122. ctx.lineTo(x + rx, y + height);
  1123. ctx.bezierCurveTo(x + rx - (KAPPA * rx), y + height, x, y + height - ry + (KAPPA * ry), x, y + height - ry);
  1124. ctx.lineTo(x, y + ry);
  1125. ctx.bezierCurveTo(x, y + ry - (KAPPA * ry), x + rx - (KAPPA * rx), y, x + rx, y);
  1126. ctx.closePath();
  1127. }
  1128. }
  1129. return new svg.BoundingBox(x, y, x + width, y + height);
  1130. };
  1131. };
  1132. svg.Element.rect.prototype = new svg.Element.PathElementBase;
  1133. // circle element
  1134. svg.Element.circle = function (node) {
  1135. this.base = svg.Element.PathElementBase;
  1136. this.base(node);
  1137. this.path = function (ctx) {
  1138. var cx = this.attribute('cx').toPixels('x');
  1139. var cy = this.attribute('cy').toPixels('y');
  1140. var r = this.attribute('r').toPixels();
  1141. if (ctx != null && r > 0) {
  1142. ctx.beginPath();
  1143. ctx.arc(cx, cy, r, 0, Math.PI * 2, false);
  1144. ctx.closePath();
  1145. }
  1146. return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);
  1147. };
  1148. };
  1149. svg.Element.circle.prototype = new svg.Element.PathElementBase;
  1150. // ellipse element
  1151. svg.Element.ellipse = function (node) {
  1152. this.base = svg.Element.PathElementBase;
  1153. this.base(node);
  1154. this.path = function (ctx) {
  1155. var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
  1156. var rx = this.attribute('rx').toPixels('x');
  1157. var ry = this.attribute('ry').toPixels('y');
  1158. var cx = this.attribute('cx').toPixels('x');
  1159. var cy = this.attribute('cy').toPixels('y');
  1160. if (ctx != null) {
  1161. ctx.beginPath();
  1162. ctx.moveTo(cx + rx, cy);
  1163. ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);
  1164. ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);
  1165. ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);
  1166. ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);
  1167. ctx.closePath();
  1168. }
  1169. return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);
  1170. };
  1171. };
  1172. svg.Element.ellipse.prototype = new svg.Element.PathElementBase;
  1173. // line element
  1174. svg.Element.line = function (node) {
  1175. this.base = svg.Element.PathElementBase;
  1176. this.base(node);
  1177. this.getPoints = function () {
  1178. return [
  1179. new svg.Point(this.attribute('x1').toPixels('x'), this.attribute('y1').toPixels('y')),
  1180. new svg.Point(this.attribute('x2').toPixels('x'), this.attribute('y2').toPixels('y'))
  1181. ];
  1182. };
  1183. this.path = function (ctx) {
  1184. var points = this.getPoints();
  1185. if (ctx != null) {
  1186. ctx.beginPath();
  1187. ctx.moveTo(points[0].x, points[0].y);
  1188. ctx.lineTo(points[1].x, points[1].y);
  1189. }
  1190. return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);
  1191. };
  1192. this.getMarkers = function () {
  1193. var points = this.getPoints();
  1194. var a = points[0].angleTo(points[1]);
  1195. return [
  1196. [points[0], a],
  1197. [points[1], a]
  1198. ];
  1199. };
  1200. };
  1201. svg.Element.line.prototype = new svg.Element.PathElementBase;
  1202. // polyline element
  1203. svg.Element.polyline = function (node) {
  1204. this.base = svg.Element.PathElementBase;
  1205. this.base(node);
  1206. this.points = svg.CreatePath(this.attribute('points').value);
  1207. this.path = function (ctx) {
  1208. var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);
  1209. if (ctx != null) {
  1210. ctx.beginPath();
  1211. ctx.moveTo(this.points[0].x, this.points[0].y);
  1212. }
  1213. for (var i = 1; i < this.points.length; i++) {
  1214. bb.addPoint(this.points[i].x, this.points[i].y);
  1215. if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);
  1216. }
  1217. return bb;
  1218. };
  1219. this.getMarkers = function () {
  1220. var markers = [];
  1221. for (var i = 0; i < this.points.length - 1; i++) {
  1222. markers.push([this.points[i], this.points[i].angleTo(this.points[i + 1])]);
  1223. }
  1224. if (markers.length > 0) {
  1225. markers.push([this.points[this.points.length - 1], markers[markers.length - 1][1]]);
  1226. }
  1227. return markers;
  1228. };
  1229. };
  1230. svg.Element.polyline.prototype = new svg.Element.PathElementBase;
  1231. // polygon element
  1232. svg.Element.polygon = function (node) {
  1233. this.base = svg.Element.polyline;
  1234. this.base(node);
  1235. this.basePath = this.path;
  1236. this.path = function (ctx) {
  1237. var bb = this.basePath(ctx);
  1238. if (ctx != null) {
  1239. ctx.lineTo(this.points[0].x, this.points[0].y);
  1240. ctx.closePath();
  1241. }
  1242. return bb;
  1243. };
  1244. };
  1245. svg.Element.polygon.prototype = new svg.Element.polyline;
  1246. // path element
  1247. svg.Element.path = function (node) {
  1248. this.base = svg.Element.PathElementBase;
  1249. this.base(node);
  1250. var d = this.attribute('d').value;
  1251. // TODO: convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF
  1252. d = d.replace(/,/gm, ' '); // get rid of all commas
  1253. // As the end of a match can also be the start of the next match, we need to run this replace twice.
  1254. for (var i = 0; i < 2; i++)
  1255. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm, '$1 $2'); // suffix commands with spaces
  1256. d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2'); // prefix commands with spaces
  1257. d = d.replace(/([0-9])([+\-])/gm, '$1 $2'); // separate digits on +- signs
  1258. // Again, we need to run this twice to find all occurances
  1259. for (var i = 0; i < 2; i++)
  1260. d = d.replace(/(\.[0-9]*)(\.)/gm, '$1 $2'); // separate digits when they start with a comma
  1261. d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm, '$1 $3 $4 '); // shorthand elliptical arc path syntax
  1262. d = svg.compressSpaces(d); // compress multiple spaces
  1263. d = svg.trim(d);
  1264. this.PathParser = new (function (d) {
  1265. this.tokens = d.split(' ');
  1266. this.reset = function () {
  1267. this.i = -1;
  1268. this.command = '';
  1269. this.previousCommand = '';
  1270. this.start = new svg.Point(0, 0);
  1271. this.control = new svg.Point(0, 0);
  1272. this.current = new svg.Point(0, 0);
  1273. this.points = [];
  1274. this.angles = [];
  1275. };
  1276. this.isEnd = function () {
  1277. return this.i >= this.tokens.length - 1;
  1278. };
  1279. this.isCommandOrEnd = function () {
  1280. if (this.isEnd()) return true;
  1281. return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null;
  1282. };
  1283. this.isRelativeCommand = function () {
  1284. switch (this.command) {
  1285. case 'm':
  1286. case 'l':
  1287. case 'h':
  1288. case 'v':
  1289. case 'c':
  1290. case 's':
  1291. case 'q':
  1292. case 't':
  1293. case 'a':
  1294. case 'z':
  1295. return true;
  1296. }
  1297. return false;
  1298. };
  1299. this.getToken = function () {
  1300. this.i++;
  1301. return this.tokens[this.i];
  1302. };
  1303. this.getScalar = function () {
  1304. return parseFloat(this.getToken());
  1305. };
  1306. this.nextCommand = function () {
  1307. this.previousCommand = this.command;
  1308. this.command = this.getToken();
  1309. };
  1310. this.getPoint = function () {
  1311. var p = new svg.Point(this.getScalar(), this.getScalar());
  1312. return this.makeAbsolute(p);
  1313. };
  1314. this.getAsControlPoint = function () {
  1315. var p = this.getPoint();
  1316. this.control = p;
  1317. return p;
  1318. };
  1319. this.getAsCurrentPoint = function () {
  1320. var p = this.getPoint();
  1321. this.current = p;
  1322. return p;
  1323. };
  1324. this.getReflectedControlPoint = function () {
  1325. if (this.previousCommand.toLowerCase() != 'c' &&
  1326. this.previousCommand.toLowerCase() != 's' &&
  1327. this.previousCommand.toLowerCase() != 'q' &&
  1328. this.previousCommand.toLowerCase() != 't') {
  1329. return this.current;
  1330. }
  1331. // reflect point
  1332. var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);
  1333. return p;
  1334. };
  1335. this.makeAbsolute = function (p) {
  1336. if (this.isRelativeCommand()) {
  1337. p.x += this.current.x;
  1338. p.y += this.current.y;
  1339. }
  1340. return p;
  1341. };
  1342. this.addMarker = function (p, from, priorTo) {
  1343. // if the last angle isn't filled in because we didn't have this point yet ...
  1344. if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length - 1] == null) {
  1345. this.angles[this.angles.length - 1] = this.points[this.points.length - 1].angleTo(priorTo);
  1346. }
  1347. this.addMarkerAngle(p, from == null ? null : from.angleTo(p));
  1348. };
  1349. this.addMarkerAngle = function (p, a) {
  1350. this.points.push(p);
  1351. this.angles.push(a);
  1352. };
  1353. this.getMarkerPoints = function () { return this.points; };
  1354. this.getMarkerAngles = function () {
  1355. for (var i = 0; i < this.angles.length; i++) {
  1356. if (this.angles[i] == null) {
  1357. for (var j = i + 1; j < this.angles.length; j++) {
  1358. if (this.angles[j] != null) {
  1359. this.angles[i] = this.angles[j];
  1360. break;
  1361. }
  1362. }
  1363. }
  1364. }
  1365. return this.angles;
  1366. };
  1367. })(d);
  1368. this.path = function (ctx) {
  1369. var pp = this.PathParser;
  1370. pp.reset();
  1371. var bb = new svg.BoundingBox();
  1372. if (ctx != null) ctx.beginPath();
  1373. while (!pp.isEnd()) {
  1374. pp.nextCommand();
  1375. switch (pp.command) {
  1376. case 'M':
  1377. case 'm':
  1378. var p = pp.getAsCurrentPoint();
  1379. pp.addMarker(p);
  1380. bb.addPoint(p.x, p.y);
  1381. if (ctx != null) ctx.moveTo(p.x, p.y);
  1382. pp.start = pp.current;
  1383. while (!pp.isCommandOrEnd()) {
  1384. var p = pp.getAsCurrentPoint();
  1385. pp.addMarker(p, pp.start);
  1386. bb.addPoint(p.x, p.y);
  1387. if (ctx != null) ctx.lineTo(p.x, p.y);
  1388. }
  1389. break;
  1390. case 'L':
  1391. case 'l':
  1392. while (!pp.isCommandOrEnd()) {
  1393. var c = pp.current;
  1394. var p = pp.getAsCurrentPoint();
  1395. pp.addMarker(p, c);
  1396. bb.addPoint(p.x, p.y);
  1397. if (ctx != null) ctx.lineTo(p.x, p.y);
  1398. }
  1399. break;
  1400. case 'H':
  1401. case 'h':
  1402. while (!pp.isCommandOrEnd()) {
  1403. var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);
  1404. pp.addMarker(newP, pp.current);
  1405. pp.current = newP;
  1406. bb.addPoint(pp.current.x, pp.current.y);
  1407. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1408. }
  1409. break;
  1410. case 'V':
  1411. case 'v':
  1412. while (!pp.isCommandOrEnd()) {
  1413. var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
  1414. pp.addMarker(newP, pp.current);
  1415. pp.current = newP;
  1416. bb.addPoint(pp.current.x, pp.current.y);
  1417. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1418. }
  1419. break;
  1420. case 'C':
  1421. case 'c':
  1422. while (!pp.isCommandOrEnd()) {
  1423. var curr = pp.current;
  1424. var p1 = pp.getPoint();
  1425. var cntrl = pp.getAsControlPoint();
  1426. var cp = pp.getAsCurrentPoint();
  1427. pp.addMarker(cp, cntrl, p1);
  1428. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1429. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1430. }
  1431. break;
  1432. case 'S':
  1433. case 's':
  1434. while (!pp.isCommandOrEnd()) {
  1435. var curr = pp.current;
  1436. var p1 = pp.getReflectedControlPoint();
  1437. var cntrl = pp.getAsControlPoint();
  1438. var cp = pp.getAsCurrentPoint();
  1439. pp.addMarker(cp, cntrl, p1);
  1440. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1441. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1442. }
  1443. break;
  1444. case 'Q':
  1445. case 'q':
  1446. while (!pp.isCommandOrEnd()) {
  1447. var curr = pp.current;
  1448. var cntrl = pp.getAsControlPoint();
  1449. var cp = pp.getAsCurrentPoint();
  1450. pp.addMarker(cp, cntrl, cntrl);
  1451. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1452. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1453. }
  1454. break;
  1455. case 'T':
  1456. case 't':
  1457. while (!pp.isCommandOrEnd()) {
  1458. var curr = pp.current;
  1459. var cntrl = pp.getReflectedControlPoint();
  1460. pp.control = cntrl;
  1461. var cp = pp.getAsCurrentPoint();
  1462. pp.addMarker(cp, cntrl, cntrl);
  1463. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1464. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1465. }
  1466. break;
  1467. case 'A':
  1468. case 'a':
  1469. while (!pp.isCommandOrEnd()) {
  1470. var curr = pp.current;
  1471. var rx = pp.getScalar();
  1472. var ry = pp.getScalar();
  1473. var xAxisRotation = pp.getScalar() * (Math.PI / 180.0);
  1474. var largeArcFlag = pp.getScalar();
  1475. var sweepFlag = pp.getScalar();
  1476. var cp = pp.getAsCurrentPoint();
  1477. // Conversion from endpoint to center parameterization
  1478. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  1479. // x1', y1'
  1480. var currp = new svg.Point(
  1481. Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0, -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
  1482. );
  1483. // adjust radii
  1484. var l = Math.pow(currp.x, 2) / Math.pow(rx, 2) + Math.pow(currp.y, 2) / Math.pow(ry, 2);
  1485. if (l > 1) {
  1486. rx *= Math.sqrt(l);
  1487. ry *= Math.sqrt(l);
  1488. }
  1489. // cx', cy'
  1490. var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
  1491. ((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))) /
  1492. (Math.pow(rx, 2) * Math.pow(currp.y, 2) + Math.pow(ry, 2) * Math.pow(currp.x, 2))
  1493. );
  1494. if (isNaN(s)) s = 0;
  1495. var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
  1496. // cx, cy
  1497. var centp = new svg.Point(
  1498. (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
  1499. (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
  1500. );
  1501. // vector magnitude
  1502. var m = function (v) { return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2)); };
  1503. // ratio between two vectors
  1504. var r = function (u, v) { return (u[0] * v[0] + u[1] * v[1]) / (m(u) * m(v)) };
  1505. // angle between two vectors
  1506. var a = function (u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(r(u, v)); };
  1507. // initial angle
  1508. var a1 = a([1, 0], [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]);
  1509. // angle delta
  1510. var u = [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry];
  1511. var v = [(-currp.x - cpp.x) / rx, (-currp.y - cpp.y) / ry];
  1512. var ad = a(u, v);
  1513. if (r(u, v) <= -1) ad = Math.PI;
  1514. if (r(u, v) >= 1) ad = 0;
  1515. // for markers
  1516. var dir = 1 - sweepFlag ? 1.0 : -1.0;
  1517. var ah = a1 + dir * (ad / 2.0);
  1518. var halfWay = new svg.Point(
  1519. centp.x + rx * Math.cos(ah),
  1520. centp.y + ry * Math.sin(ah)
  1521. );
  1522. pp.addMarkerAngle(halfWay, ah - dir * Math.PI / 2);
  1523. pp.addMarkerAngle(cp, ah - dir * Math.PI);
  1524. bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better
  1525. if (ctx != null && !isNaN(a1) && !isNaN(ad)) {
  1526. var r = rx > ry ? rx : ry;
  1527. var sx = rx > ry ? 1 : rx / ry;
  1528. var sy = rx > ry ? ry / rx : 1;
  1529. ctx.translate(centp.x, centp.y);
  1530. ctx.rotate(xAxisRotation);
  1531. ctx.scale(sx, sy);
  1532. ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);
  1533. ctx.scale(1 / sx, 1 / sy);
  1534. ctx.rotate(-xAxisRotation);
  1535. ctx.translate(-centp.x, -centp.y);
  1536. }
  1537. }
  1538. break;
  1539. case 'Z':
  1540. case 'z':
  1541. if (ctx != null) {
  1542. // only close path if it is not a straight line
  1543. if (bb.x1 !== bb.x2 && bb.y1 !== bb.y2) {
  1544. ctx.closePath();
  1545. }
  1546. }
  1547. pp.current = pp.start;
  1548. }
  1549. }
  1550. return bb;
  1551. };
  1552. this.getMarkers = function () {
  1553. var points = this.PathParser.getMarkerPoints();
  1554. var angles = this.PathParser.getMarkerAngles();
  1555. var markers = [];
  1556. for (var i = 0; i < points.length; i++) {
  1557. markers.push([points[i], angles[i]]);
  1558. }
  1559. return markers;
  1560. };
  1561. };
  1562. svg.Element.path.prototype = new svg.Element.PathElementBase;
  1563. // pattern element
  1564. svg.Element.pattern = function (node) {
  1565. this.base = svg.Element.ElementBase;
  1566. this.base(node);
  1567. this.createPattern = function (ctx, element, parentOpacityProp) {
  1568. var width = this.attribute('width').toPixels('x', true);
  1569. var height = this.attribute('height').toPixels('y', true);
  1570. // render me using a temporary svg element
  1571. var tempSvg = new svg.Element.svg();
  1572. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1573. tempSvg.attributes['width'] = new svg.Property('width', width + 'px');
  1574. tempSvg.attributes['height'] = new svg.Property('height', height + 'px');
  1575. tempSvg.attributes['transform'] = new svg.Property('transform', this.attribute('patternTransform').value);
  1576. tempSvg.children = this.children;
  1577. var c = createCanvas(width, height);
  1578. var cctx = c.getContext('2d');
  1579. if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {
  1580. cctx.translate(this.attribute('x').toPixels('x', true), this.attribute('y').toPixels('y', true));
  1581. }
  1582. if (parentOpacityProp.hasValue()) {
  1583. this.styles['fill-opacity'] = parentOpacityProp;
  1584. } else {
  1585. delete this.styles['fill-opacity'];
  1586. }
  1587. // render 3x3 grid so when we transform there's no white space on edges
  1588. for (var x = -1; x <= 1; x++) {
  1589. for (var y = -1; y <= 1; y++) {
  1590. cctx.save();
  1591. tempSvg.attributes['x'] = new svg.Property('x', x * c.width);
  1592. tempSvg.attributes['y'] = new svg.Property('y', y * c.height);
  1593. tempSvg.render(cctx);
  1594. cctx.restore();
  1595. }
  1596. }
  1597. var pattern = ctx.createPattern(c, 'repeat');
  1598. return pattern;
  1599. };
  1600. };
  1601. svg.Element.pattern.prototype = new svg.Element.ElementBase;
  1602. // marker element
  1603. svg.Element.marker = function (node) {
  1604. this.base = svg.Element.ElementBase;
  1605. this.base(node);
  1606. this.baseRender = this.render;
  1607. this.render = function (ctx, point, angle) {
  1608. if (!point) { return; }
  1609. ctx.translate(point.x, point.y);
  1610. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle);
  1611. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);
  1612. ctx.save();
  1613. // render me using a temporary svg element
  1614. var tempSvg = new svg.Element.svg();
  1615. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1616. tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);
  1617. tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);
  1618. tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);
  1619. tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);
  1620. tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));
  1621. tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));
  1622. tempSvg.children = this.children;
  1623. tempSvg.render(ctx);
  1624. ctx.restore();
  1625. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1 / ctx.lineWidth, 1 / ctx.lineWidth);
  1626. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle);
  1627. ctx.translate(-point.x, -point.y);
  1628. };
  1629. };
  1630. svg.Element.marker.prototype = new svg.Element.ElementBase;
  1631. // definitions element
  1632. svg.Element.defs = function (node) {
  1633. this.base = svg.Element.ElementBase;
  1634. this.base(node);
  1635. this.render = function (/* ctx */) {
  1636. // NOOP
  1637. };
  1638. };
  1639. svg.Element.defs.prototype = new svg.Element.ElementBase;
  1640. // base for gradients
  1641. svg.Element.GradientBase = function (node) {
  1642. this.base = svg.Element.ElementBase;
  1643. this.base(node);
  1644. this.stops = [];
  1645. for (var i = 0; i < this.children.length; i++) {
  1646. var child = this.children[i];
  1647. if (child.type == 'stop') this.stops.push(child);
  1648. }
  1649. this.getGradient = function () {
  1650. // OVERRIDE ME!
  1651. };
  1652. this.gradientUnits = function () {
  1653. return this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');
  1654. };
  1655. this.attributesToInherit = ['gradientUnits'];
  1656. this.inheritStopContainer = function (stopsContainer) {
  1657. for (var i = 0; i < this.attributesToInherit.length; i++) {
  1658. var attributeToInherit = this.attributesToInherit[i];
  1659. if (!this.attribute(attributeToInherit).hasValue() && stopsContainer.attribute(attributeToInherit).hasValue()) {
  1660. this.attribute(attributeToInherit, true).value = stopsContainer.attribute(attributeToInherit).value;
  1661. }
  1662. }
  1663. };
  1664. this.createGradient = function (ctx, element, parentOpacityProp) {
  1665. var stopsContainer = this;
  1666. if (this.getHrefAttribute().hasValue()) {
  1667. stopsContainer = this.getHrefAttribute().getDefinition();
  1668. this.inheritStopContainer(stopsContainer);
  1669. }
  1670. var addParentOpacity = function (color) {
  1671. if (parentOpacityProp.hasValue()) {
  1672. var p = new svg.Property('color', color);
  1673. return p.addOpacity(parentOpacityProp).value;
  1674. }
  1675. return color;
  1676. };
  1677. var g = this.getGradient(ctx, element);
  1678. if (g == null) return addParentOpacity(stopsContainer.stops[stopsContainer.stops.length - 1].color);
  1679. for (var i = 0; i < stopsContainer.stops.length; i++) {
  1680. g.addColorStop(stopsContainer.stops[i].offset, addParentOpacity(stopsContainer.stops[i].color));
  1681. }
  1682. if (this.attribute('gradientTransform').hasValue()) {
  1683. // render as transformed pattern on temporary canvas
  1684. var rootView = svg.ViewPort.viewPorts[0];
  1685. var rect = new svg.Element.rect();
  1686. rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS / 3.0);
  1687. rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS / 3.0);
  1688. rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS);
  1689. rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS);
  1690. var group = new svg.Element.g();
  1691. group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value);
  1692. group.children = [rect];
  1693. var tempSvg = new svg.Element.svg();
  1694. tempSvg.attributes['x'] = new svg.Property('x', 0);
  1695. tempSvg.attributes['y'] = new svg.Property('y', 0);
  1696. tempSvg.attributes['width'] = new svg.Property('width', rootView.width);
  1697. tempSvg.attributes['height'] = new svg.Property('height', rootView.height);
  1698. tempSvg.children = [group];
  1699. var c = createCanvas(rootView.width, rootView.height);
  1700. var tempCtx = c.getContext('2d');
  1701. tempCtx.fillStyle = g;
  1702. tempSvg.render(tempCtx);
  1703. return tempCtx.createPattern(c, 'no-repeat');
  1704. }
  1705. return g;
  1706. };
  1707. };
  1708. svg.Element.GradientBase.prototype = new svg.Element.ElementBase;
  1709. // linear gradient element
  1710. svg.Element.linearGradient = function (node) {
  1711. this.base = svg.Element.GradientBase;
  1712. this.base(node);
  1713. this.attributesToInherit.push('x1');
  1714. this.attributesToInherit.push('y1');
  1715. this.attributesToInherit.push('x2');
  1716. this.attributesToInherit.push('y2');
  1717. this.getGradient = function (ctx, element) {
  1718. var bb = this.gradientUnits() == 'objectBoundingBox' ? element.getBoundingBox(ctx) : null;
  1719. if (!this.attribute('x1').hasValue() &&
  1720. !this.attribute('y1').hasValue() &&
  1721. !this.attribute('x2').hasValue() &&
  1722. !this.attribute('y2').hasValue()) {
  1723. this.attribute('x1', true).value = 0;
  1724. this.attribute('y1', true).value = 0;
  1725. this.attribute('x2', true).value = 1;
  1726. this.attribute('y2', true).value = 0;
  1727. }
  1728. var x1 = (this.gradientUnits() == 'objectBoundingBox' ?
  1729. bb.x() + bb.width() * this.attribute('x1').numValue() :
  1730. this.attribute('x1').toPixels('x'));
  1731. var y1 = (this.gradientUnits() == 'objectBoundingBox' ?
  1732. bb.y() + bb.height() * this.attribute('y1').numValue() :
  1733. this.attribute('y1').toPixels('y'));
  1734. var x2 = (this.gradientUnits() == 'objectBoundingBox' ?
  1735. bb.x() + bb.width() * this.attribute('x2').numValue() :
  1736. this.attribute('x2').toPixels('x'));
  1737. var y2 = (this.gradientUnits() == 'objectBoundingBox' ?
  1738. bb.y() + bb.height() * this.attribute('y2').numValue() :
  1739. this.attribute('y2').toPixels('y'));
  1740. if (x1 == x2 && y1 == y2) return null;
  1741. return ctx.createLinearGradient(x1, y1, x2, y2);
  1742. };
  1743. };
  1744. svg.Element.linearGradient.prototype = new svg.Element.GradientBase;
  1745. // radial gradient element
  1746. svg.Element.radialGradient = function (node) {
  1747. this.base = svg.Element.GradientBase;
  1748. this.base(node);
  1749. this.attributesToInherit.push('cx');
  1750. this.attributesToInherit.push('cy');
  1751. this.attributesToInherit.push('r');
  1752. this.attributesToInherit.push('fx');
  1753. this.attributesToInherit.push('fy');
  1754. this.attributesToInherit.push('fr');
  1755. this.getGradient = function (ctx, element) {
  1756. var bb = element.getBoundingBox(ctx);
  1757. if (!this.attribute('cx').hasValue()) this.attribute('cx', true).value = '50%';
  1758. if (!this.attribute('cy').hasValue()) this.attribute('cy', true).value = '50%';
  1759. if (!this.attribute('r').hasValue()) this.attribute('r', true).value = '50%';
  1760. var cx = (this.gradientUnits() == 'objectBoundingBox' ?
  1761. bb.x() + bb.width() * this.attribute('cx').numValue() :
  1762. this.attribute('cx').toPixels('x'));
  1763. var cy = (this.gradientUnits() == 'objectBoundingBox' ?
  1764. bb.y() + bb.height() * this.attribute('cy').numValue() :
  1765. this.attribute('cy').toPixels('y'));
  1766. var fx = cx;
  1767. var fy = cy;
  1768. if (this.attribute('fx').hasValue()) {
  1769. fx = (this.gradientUnits() == 'objectBoundingBox' ?
  1770. bb.x() + bb.width() * this.attribute('fx').numValue() :
  1771. this.attribute('fx').toPixels('x'));
  1772. }
  1773. if (this.attribute('fy').hasValue()) {
  1774. fy = (this.gradientUnits() == 'objectBoundingBox' ?
  1775. bb.y() + bb.height() * this.attribute('fy').numValue() :
  1776. this.attribute('fy').toPixels('y'));
  1777. }
  1778. var r = (this.gradientUnits() == 'objectBoundingBox' ?
  1779. (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue() :
  1780. this.attribute('r').toPixels());
  1781. var fr = this.attribute('fr').toPixels();
  1782. return ctx.createRadialGradient(fx, fy, fr, cx, cy, r);
  1783. };
  1784. };
  1785. svg.Element.radialGradient.prototype = new svg.Element.GradientBase;
  1786. // gradient stop element
  1787. svg.Element.stop = function (node) {
  1788. this.base = svg.Element.ElementBase;
  1789. this.base(node);
  1790. this.offset = this.attribute('offset').numValue();
  1791. if (this.offset < 0) this.offset = 0;
  1792. if (this.offset > 1) this.offset = 1;
  1793. var stopColor = this.style('stop-color', true);
  1794. if (stopColor.value === '') stopColor.value = '#000';
  1795. if (this.style('stop-opacity').hasValue()) stopColor = stopColor.addOpacity(this.style('stop-opacity'));
  1796. this.color = stopColor.value;
  1797. };
  1798. svg.Element.stop.prototype = new svg.Element.ElementBase;
  1799. // animation base element
  1800. svg.Element.AnimateBase = function (node) {
  1801. this.base = svg.Element.ElementBase;
  1802. this.base(node);
  1803. svg.Animations.push(this);
  1804. this.duration = 0.0;
  1805. this.begin = this.attribute('begin').toMilliseconds();
  1806. this.maxDuration = this.begin + this.attribute('dur').toMilliseconds();
  1807. this.getProperty = function () {
  1808. var attributeType = this.attribute('attributeType').value;
  1809. var attributeName = this.attribute('attributeName').value;
  1810. if (attributeType == 'CSS') {
  1811. return this.parent.style(attributeName, true);
  1812. }
  1813. return this.parent.attribute(attributeName, true);
  1814. };
  1815. this.initialValue = null;
  1816. this.initialUnits = '';
  1817. this.removed = false;
  1818. this.calcValue = function () {
  1819. // OVERRIDE ME!
  1820. return '';
  1821. };
  1822. this.update = function (delta) {
  1823. // set initial value
  1824. if (this.initialValue == null) {
  1825. this.initialValue = this.getProperty().value;
  1826. this.initialUnits = this.getProperty().getUnits();
  1827. }
  1828. // if we're past the end time
  1829. if (this.duration > this.maxDuration) {
  1830. // loop for indefinitely repeating animations
  1831. if (this.attribute('repeatCount').value == 'indefinite' ||
  1832. this.attribute('repeatDur').value == 'indefinite') {
  1833. this.duration = 0.0;
  1834. } else if (this.attribute('fill').valueOrDefault('remove') == 'freeze' && !this.frozen) {
  1835. this.frozen = true;
  1836. this.parent.animationFrozen = true;
  1837. this.parent.animationFrozenValue = this.getProperty().value;
  1838. } else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) {
  1839. this.removed = true;
  1840. this.getProperty().value = this.parent.animationFrozen ? this.parent.animationFrozenValue : this.initialValue;
  1841. return true;
  1842. }
  1843. return false;
  1844. }
  1845. this.duration = this.duration + delta;
  1846. // if we're past the begin time
  1847. var updated = false;
  1848. if (this.begin < this.duration) {
  1849. var newValue = this.calcValue(); // tween
  1850. if (this.attribute('type').hasValue()) {
  1851. // for transform, etc.
  1852. var type = this.attribute('type').value;
  1853. newValue = type + '(' + newValue + ')';
  1854. }
  1855. this.getProperty().value = newValue;
  1856. updated = true;
  1857. }
  1858. return updated;
  1859. };
  1860. this.from = this.attribute('from');
  1861. this.to = this.attribute('to');
  1862. this.values = this.attribute('values');
  1863. if (this.values.hasValue()) this.values.value = this.values.value.split(';');
  1864. // fraction of duration we've covered
  1865. this.progress = function () {
  1866. var ret = { progress: (this.duration - this.begin) / (this.maxDuration - this.begin) };
  1867. if (this.values.hasValue()) {
  1868. var p = ret.progress * (this.values.value.length - 1);
  1869. var lb = Math.floor(p),
  1870. ub = Math.ceil(p);
  1871. ret.from = new svg.Property('from', parseFloat(this.values.value[lb]));
  1872. ret.to = new svg.Property('to', parseFloat(this.values.value[ub]));
  1873. ret.progress = (p - lb) / (ub - lb);
  1874. } else {
  1875. ret.from = this.from;
  1876. ret.to = this.to;
  1877. }
  1878. return ret;
  1879. };
  1880. };
  1881. svg.Element.AnimateBase.prototype = new svg.Element.ElementBase;
  1882. // animate element
  1883. svg.Element.animate = function (node) {
  1884. this.base = svg.Element.AnimateBase;
  1885. this.base(node);
  1886. this.calcValue = function () {
  1887. var p = this.progress();
  1888. // tween value linearly
  1889. var newValue = p.from.numValue() + (p.to.numValue() - p.from.numValue()) * p.progress;
  1890. if (this.initialUnits === '%') {
  1891. newValue *= 100.0; // numValue() returns 0-1 whereas properties are 0-100
  1892. }
  1893. return newValue + this.initialUnits;
  1894. };
  1895. };
  1896. svg.Element.animate.prototype = new svg.Element.AnimateBase;
  1897. // animate color element
  1898. svg.Element.animateColor = function (node) {
  1899. this.base = svg.Element.AnimateBase;
  1900. this.base(node);
  1901. this.calcValue = function () {
  1902. var p = this.progress();
  1903. var from = new rgbcolor(p.from.value);
  1904. var to = new rgbcolor(p.to.value);
  1905. if (from.ok && to.ok) {
  1906. // tween color linearly
  1907. var r = from.r + (to.r - from.r) * p.progress;
  1908. var g = from.g + (to.g - from.g) * p.progress;
  1909. var b = from.b + (to.b - from.b) * p.progress;
  1910. return 'rgb(' + parseInt(r, 10) + ',' + parseInt(g, 10) + ',' + parseInt(b, 10) + ')';
  1911. }
  1912. return this.attribute('from').value;
  1913. };
  1914. };
  1915. svg.Element.animateColor.prototype = new svg.Element.AnimateBase;
  1916. // animate transform element
  1917. svg.Element.animateTransform = function (node) {
  1918. this.base = svg.Element.AnimateBase;
  1919. this.base(node);
  1920. this.calcValue = function () {
  1921. var p = this.progress();
  1922. // tween value linearly
  1923. var from = svg.ToNumberArray(p.from.value);
  1924. var to = svg.ToNumberArray(p.to.value);
  1925. var newValue = '';
  1926. for (var i = 0; i < from.length; i++) {
  1927. newValue += from[i] + (to[i] - from[i]) * p.progress + ' ';
  1928. }
  1929. return newValue;
  1930. };
  1931. };
  1932. svg.Element.animateTransform.prototype = new svg.Element.animate;
  1933. // font element
  1934. svg.Element.font = function (node) {
  1935. this.base = svg.Element.ElementBase;
  1936. this.base(node);
  1937. this.horizAdvX = this.attribute('horiz-adv-x').numValue();
  1938. this.isRTL = false;
  1939. this.isArabic = false;
  1940. this.fontFace = null;
  1941. this.missingGlyph = null;
  1942. this.glyphs = [];
  1943. for (var i = 0; i < this.children.length; i++) {
  1944. var child = this.children[i];
  1945. if (child.type == 'font-face') {
  1946. this.fontFace = child;
  1947. if (child.style('font-family').hasValue()) {
  1948. svg.Definitions[child.style('font-family').value] = this;
  1949. }
  1950. } else if (child.type == 'missing-glyph') this.missingGlyph = child;
  1951. else if (child.type == 'glyph') {
  1952. if (child.arabicForm != '') {
  1953. this.isRTL = true;
  1954. this.isArabic = true;
  1955. if (typeof this.glyphs[child.unicode] == 'undefined') this.glyphs[child.unicode] = [];
  1956. this.glyphs[child.unicode][child.arabicForm] = child;
  1957. } else {
  1958. this.glyphs[child.unicode] = child;
  1959. }
  1960. }
  1961. }
  1962. this.render = function (/* ctx */) {
  1963. // NO RENDER
  1964. };
  1965. };
  1966. svg.Element.font.prototype = new svg.Element.ElementBase;
  1967. // font-face element
  1968. svg.Element.fontface = function (node) {
  1969. this.base = svg.Element.ElementBase;
  1970. this.base(node);
  1971. this.ascent = this.attribute('ascent').value;
  1972. this.descent = this.attribute('descent').value;
  1973. this.unitsPerEm = this.attribute('units-per-em').numValue();
  1974. };
  1975. svg.Element.fontface.prototype = new svg.Element.ElementBase;
  1976. // missing-glyph element
  1977. svg.Element.missingglyph = function (node) {
  1978. this.base = svg.Element.path;
  1979. this.base(node);
  1980. this.horizAdvX = 0;
  1981. };
  1982. svg.Element.missingglyph.prototype = new svg.Element.path;
  1983. // glyph element
  1984. svg.Element.glyph = function (node) {
  1985. this.base = svg.Element.path;
  1986. this.base(node);
  1987. this.horizAdvX = this.attribute('horiz-adv-x').numValue();
  1988. this.unicode = this.attribute('unicode').value;
  1989. this.arabicForm = this.attribute('arabic-form').value;
  1990. };
  1991. svg.Element.glyph.prototype = new svg.Element.path;
  1992. // text element
  1993. svg.Element.text = function (node) {
  1994. this.captureTextNodes = true;
  1995. this.base = svg.Element.RenderedElementBase;
  1996. this.base(node);
  1997. this.baseSetContext = this.setContext;
  1998. this.setContext = function (ctx) {
  1999. this.baseSetContext(ctx);
  2000. var textBaseline = this.style('dominant-baseline').toTextBaseline();
  2001. if (textBaseline == null) textBaseline = this.style('alignment-baseline').toTextBaseline();
  2002. if (textBaseline != null) ctx.textBaseline = textBaseline;
  2003. };
  2004. this.initializeCoordinates = function (ctx) {
  2005. this.x = this.attribute('x').toPixels('x');
  2006. this.y = this.attribute('y').toPixels('y');
  2007. if (this.attribute('dx').hasValue()) this.x += this.attribute('dx').toPixels('x');
  2008. if (this.attribute('dy').hasValue()) this.y += this.attribute('dy').toPixels('y');
  2009. this.x += this.getAnchorDelta(ctx, this, 0);
  2010. };
  2011. this.getBoundingBox = function (ctx) {
  2012. this.initializeCoordinates(ctx);
  2013. var bb = null;
  2014. for (var i = 0; i < this.children.length; i++) {
  2015. var childBB = this.getChildBoundingBox(ctx, this, this, i);
  2016. if (bb == null) bb = childBB;
  2017. else bb.addBoundingBox(childBB);
  2018. }
  2019. return bb;
  2020. };
  2021. this.renderChildren = function (ctx) {
  2022. this.initializeCoordinates(ctx);
  2023. for (var i = 0; i < this.children.length; i++) {
  2024. this.renderChild(ctx, this, this, i);
  2025. }
  2026. svg.Mouse.checkBoundingBox(this, this.getBoundingBox(ctx));
  2027. };
  2028. this.getAnchorDelta = function (ctx, parent, startI) {
  2029. var textAnchor = this.style('text-anchor').valueOrDefault('start');
  2030. if (textAnchor != 'start') {
  2031. var width = 0;
  2032. for (var i = startI; i < parent.children.length; i++) {
  2033. var child = parent.children[i];
  2034. if (i > startI && child.attribute('x').hasValue()) break; // new group
  2035. width += child.measureTextRecursive(ctx);
  2036. }
  2037. return -1 * (textAnchor == 'end' ? width : width / 2.0);
  2038. }
  2039. return 0;
  2040. };
  2041. this.adjustChildCoordinates = function (ctx, textParent, parent, i) {
  2042. var child = parent.children[i];
  2043. if (typeof (child.measureText) !== 'function') {
  2044. return child;
  2045. }
  2046. if (child.attribute('x').hasValue()) {
  2047. child.x = child.attribute('x').toPixels('x') + textParent.getAnchorDelta(ctx, parent, i);
  2048. // local text-anchor
  2049. var textAnchor = child.attribute('text-anchor').valueOrDefault('start');
  2050. if (textAnchor !== 'start') {
  2051. var width = child.measureTextRecursive(ctx);
  2052. child.x += -1 * (textAnchor == 'end' ? width : width / 2.0);
  2053. }
  2054. if (child.attribute('dx').hasValue()) child.x += child.attribute('dx').toPixels('x');
  2055. } else {
  2056. if (child.attribute('dx').hasValue()) textParent.x += child.attribute('dx').toPixels('x');
  2057. child.x = textParent.x;
  2058. }
  2059. textParent.x = child.x + child.measureText(ctx);
  2060. if (child.attribute('y').hasValue()) {
  2061. child.y = child.attribute('y').toPixels('y');
  2062. if (child.attribute('dy').hasValue()) child.y += child.attribute('dy').toPixels('y');
  2063. } else {
  2064. if (child.attribute('dy').hasValue()) textParent.y += child.attribute('dy').toPixels('y');
  2065. child.y = textParent.y;
  2066. }
  2067. textParent.y = child.y;
  2068. return child;
  2069. };
  2070. this.getChildBoundingBox = function (ctx, textParent, parent, i) {
  2071. var child = this.adjustChildCoordinates(ctx, textParent, parent, i);
  2072. var bb = child.getBoundingBox(ctx);
  2073. for (var i = 0; i < child.children.length; i++) {
  2074. var childBB = textParent.getChildBoundingBox(ctx, textParent, child, i);
  2075. bb.addBoundingBox(childBB);
  2076. }
  2077. return bb;
  2078. };
  2079. this.renderChild = function (ctx, textParent, parent, i) {
  2080. var child = this.adjustChildCoordinates(ctx, textParent, parent, i);
  2081. child.render(ctx);
  2082. for (var i = 0; i < child.children.length; i++) {
  2083. textParent.renderChild(ctx, textParent, child, i);
  2084. }
  2085. };
  2086. };
  2087. svg.Element.text.prototype = new svg.Element.RenderedElementBase;
  2088. // text base
  2089. svg.Element.TextElementBase = function (node) {
  2090. this.base = svg.Element.RenderedElementBase;
  2091. this.base(node);
  2092. this.getGlyph = function (font, text, i) {
  2093. var c = text[i];
  2094. var glyph = null;
  2095. if (font.isArabic) {
  2096. var arabicForm = 'isolated';
  2097. if ((i == 0 || text[i - 1] == ' ') && i < text.length - 2 && text[i + 1] != ' ') arabicForm = 'terminal';
  2098. if (i > 0 && text[i - 1] != ' ' && i < text.length - 2 && text[i + 1] != ' ') arabicForm = 'medial';
  2099. if (i > 0 && text[i - 1] != ' ' && (i == text.length - 1 || text[i + 1] == ' ')) arabicForm = 'initial';
  2100. if (typeof font.glyphs[c] != 'undefined') {
  2101. glyph = font.glyphs[c][arabicForm];
  2102. if (glyph == null && font.glyphs[c].type == 'glyph') glyph = font.glyphs[c];
  2103. }
  2104. } else {
  2105. glyph = font.glyphs[c];
  2106. }
  2107. if (glyph == null) glyph = font.missingGlyph;
  2108. return glyph;
  2109. };
  2110. this.renderChildren = function (ctx) {
  2111. var customFont = this.parent.style('font-family').getDefinition();
  2112. if (customFont != null) {
  2113. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  2114. var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle);
  2115. var text = this.getText();
  2116. if (customFont.isRTL) text = text.split('').reverse().join('');
  2117. var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
  2118. for (var i = 0; i < text.length; i++) {
  2119. var glyph = this.getGlyph(customFont, text, i);
  2120. var scale = fontSize / customFont.fontFace.unitsPerEm;
  2121. ctx.translate(this.x, this.y);
  2122. ctx.scale(scale, -scale);
  2123. var lw = ctx.lineWidth;
  2124. ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize;
  2125. if (fontStyle == 'italic') ctx.transform(1, 0, .4, 1, 0, 0);
  2126. glyph.render(ctx);
  2127. if (fontStyle == 'italic') ctx.transform(1, 0, -.4, 1, 0, 0);
  2128. ctx.lineWidth = lw;
  2129. ctx.scale(1 / scale, -1 / scale);
  2130. ctx.translate(-this.x, -this.y);
  2131. this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm;
  2132. if (typeof dx[i] != 'undefined' && !isNaN(dx[i])) {
  2133. this.x += dx[i];
  2134. }
  2135. }
  2136. return;
  2137. }
  2138. if (ctx.paintOrder == 'stroke') {
  2139. if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y);
  2140. if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
  2141. } else {
  2142. if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
  2143. if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y);
  2144. }
  2145. };
  2146. this.getText = function () {
  2147. // OVERRIDE ME
  2148. };
  2149. this.measureTextRecursive = function (ctx) {
  2150. var width = this.measureText(ctx);
  2151. for (var i = 0; i < this.children.length; i++) {
  2152. width += this.children[i].measureTextRecursive(ctx);
  2153. }
  2154. return width;
  2155. };
  2156. this.measureText = function (ctx) {
  2157. var customFont = this.parent.style('font-family').getDefinition();
  2158. if (customFont != null) {
  2159. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  2160. var measure = 0;
  2161. var text = this.getText();
  2162. if (customFont.isRTL) text = text.split('').reverse().join('');
  2163. var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
  2164. for (var i = 0; i < text.length; i++) {
  2165. var glyph = this.getGlyph(customFont, text, i);
  2166. measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm;
  2167. if (typeof dx[i] != 'undefined' && !isNaN(dx[i])) {
  2168. measure += dx[i];
  2169. }
  2170. }
  2171. return measure;
  2172. }
  2173. var textToMeasure = svg.compressSpaces(this.getText());
  2174. if (!ctx.measureText) return textToMeasure.length * 10;
  2175. ctx.save();
  2176. this.setContext(ctx, true);
  2177. var width = ctx.measureText(textToMeasure).width;
  2178. ctx.restore();
  2179. return width;
  2180. };
  2181. this.getBoundingBox = function (ctx) {
  2182. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  2183. return new svg.BoundingBox(this.x, this.y - fontSize, this.x + this.measureText(ctx), this.y);
  2184. };
  2185. };
  2186. svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase;
  2187. // tspan
  2188. svg.Element.tspan = function (node) {
  2189. this.captureTextNodes = true;
  2190. this.base = svg.Element.TextElementBase;
  2191. this.base(node);
  2192. this.text = svg.compressSpaces(node.value || node.text || node.textContent || '');
  2193. this.getText = function () {
  2194. // if this node has children, then they own the text
  2195. if (this.children.length > 0) { return ''; }
  2196. return this.text;
  2197. };
  2198. };
  2199. svg.Element.tspan.prototype = new svg.Element.TextElementBase;
  2200. // tref
  2201. svg.Element.tref = function (node) {
  2202. this.base = svg.Element.TextElementBase;
  2203. this.base(node);
  2204. this.getText = function () {
  2205. var element = this.getHrefAttribute().getDefinition();
  2206. if (element != null) return element.children[0].getText();
  2207. };
  2208. };
  2209. svg.Element.tref.prototype = new svg.Element.TextElementBase;
  2210. // a element
  2211. svg.Element.a = function (node) {
  2212. this.base = svg.Element.TextElementBase;
  2213. this.base(node);
  2214. this.hasText = node.childNodes.length > 0;
  2215. for (var i = 0; i < node.childNodes.length; i++) {
  2216. if (node.childNodes[i].nodeType != 3) this.hasText = false;
  2217. }
  2218. // this might contain text
  2219. this.text = this.hasText ? node.childNodes[0].value || node.childNodes[0].data : '';
  2220. this.getText = function () {
  2221. return this.text;
  2222. };
  2223. this.baseRenderChildren = this.renderChildren;
  2224. this.renderChildren = function (ctx) {
  2225. if (this.hasText) {
  2226. // render as text element
  2227. this.baseRenderChildren(ctx);
  2228. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  2229. svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.toPixels('y'), this.x + this.measureText(ctx), this.y));
  2230. } else if (this.children.length > 0) {
  2231. // render as temporary group
  2232. var g = new svg.Element.g();
  2233. g.children = this.children;
  2234. g.parent = this;
  2235. g.render(ctx);
  2236. }
  2237. };
  2238. this.onclick = function () {
  2239. windowEnv.open(this.getHrefAttribute().value);
  2240. };
  2241. this.onmousemove = function () {
  2242. svg.ctx.canvas.style.cursor = 'pointer';
  2243. };
  2244. };
  2245. svg.Element.a.prototype = new svg.Element.TextElementBase;
  2246. // textPath
  2247. svg.Element.textPath = function (node) {
  2248. this.base = svg.Element.TextElementBase;
  2249. this.base(node);
  2250. var pathElement = this.getHrefAttribute().getDefinition();
  2251. this.text = svg.compressSpaces(node.value || node.text || node.textContent || '');
  2252. this.renderChildren = function (ctx) {
  2253. this.setTextData(ctx);
  2254. ctx.save();
  2255. var textDecoration = this.parent.style('text-decoration').value;
  2256. var fontSize = this.fontSize();
  2257. var glyphInfo = this.glyphInfo;
  2258. var fill = ctx.fillStyle;
  2259. if (textDecoration === 'underline') {
  2260. ctx.beginPath();
  2261. }
  2262. for (var i = 0; i < glyphInfo.length; i++) {
  2263. var p0 = glyphInfo[i].p0;
  2264. var p1 = glyphInfo[i].p1;
  2265. var partialText = glyphInfo[i].text;
  2266. ctx.save();
  2267. ctx.translate(p0.x, p0.y);
  2268. ctx.rotate(glyphInfo[i].rotation);
  2269. if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(partialText), 0, 0);
  2270. if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(partialText), 0, 0);
  2271. ctx.restore();
  2272. if (textDecoration === 'underline') {
  2273. if (i === 0) {
  2274. ctx.moveTo(p0.x, p0.y + fontSize / 8);
  2275. }
  2276. ctx.lineTo(p1.x, p1.y + fontSize / 5);
  2277. }
  2278. //// To assist with debugging visually, uncomment following
  2279. //
  2280. // ctx.beginPath();
  2281. // if (i % 2)
  2282. // ctx.strokeStyle = 'red';
  2283. // else
  2284. // ctx.strokeStyle = 'green';
  2285. // ctx.moveTo(p0.x, p0.y);
  2286. // ctx.lineTo(p1.x, p1.y);
  2287. // ctx.stroke();
  2288. // ctx.closePath();
  2289. }
  2290. if (textDecoration === 'underline') {
  2291. ctx.lineWidth = fontSize / 20;
  2292. ctx.strokeStyle = fill;
  2293. ctx.stroke();
  2294. ctx.closePath();
  2295. }
  2296. ctx.restore();
  2297. };
  2298. this.path = function (ctx) {
  2299. var ca = this.dataArray;
  2300. if (ctx != null) {
  2301. ctx.beginPath();
  2302. }
  2303. for (var n = 0; n < ca.length; n++) {
  2304. var c = ca[n].command;
  2305. var p = ca[n].points;
  2306. switch (c) {
  2307. case 'L':
  2308. if (ctx != null) ctx.lineTo(p[0], p[1]);
  2309. break;
  2310. case 'M':
  2311. if (ctx != null) ctx.moveTo(p[0], p[1]);
  2312. break;
  2313. case 'C':
  2314. if (ctx != null) ctx.bezierCurveTo(p[0], p[1], p[2], p[3], p[4], p[5]);
  2315. break;
  2316. case 'Q':
  2317. if (ctx != null) ctx.quadraticCurveTo(p[0], p[1], p[2], p[3]);
  2318. break;
  2319. case 'A':
  2320. var cx = p[0], cy = p[1], rx = p[2], ry = p[3],
  2321. theta = p[4], dTheta = p[5], psi = p[6], fs = p[7];
  2322. var r = (rx > ry) ? rx : ry;
  2323. var scaleX = (rx > ry) ? 1 : rx / ry;
  2324. var scaleY = (rx > ry) ? ry / rx : 1;
  2325. if (ctx != null) {
  2326. ctx.translate(cx, cy);
  2327. ctx.rotate(psi);
  2328. ctx.scale(scaleX, scaleY);
  2329. ctx.arc(0, 0, r, theta, theta + dTheta, 1 - fs);
  2330. ctx.scale(1 / scaleX, 1 / scaleY);
  2331. ctx.rotate(-psi);
  2332. ctx.translate(-cx, -cy);
  2333. }
  2334. break;
  2335. case 'z':
  2336. if (ctx != null) ctx.closePath();
  2337. break;
  2338. }
  2339. }
  2340. };
  2341. this.getText = function () {
  2342. return this.text;
  2343. };
  2344. this.fontSize = function () {
  2345. return this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  2346. };
  2347. this.measureText = function (ctx, text) {
  2348. var customFont = this.parent.style('font-family').getDefinition();
  2349. text = text || this.getText();
  2350. if (customFont != null) {
  2351. var fontSize = this.fontSize();
  2352. var measure = 0;
  2353. if (customFont.isRTL) text = text.split("").reverse().join("");
  2354. var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
  2355. for (var i = 0; i < text.length; i++) {
  2356. var glyph = this.getGlyph(customFont, text, i);
  2357. measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm;
  2358. if (typeof dx[i] != 'undefined' && !isNaN(dx[i])) {
  2359. measure += dx[i];
  2360. }
  2361. }
  2362. return measure;
  2363. }
  2364. var textToMeasure = svg.compressSpaces(text);
  2365. if (!ctx.measureText) return textToMeasure.length * 10;
  2366. ctx.save();
  2367. this.setContext(ctx);
  2368. var width = ctx.measureText(textToMeasure).width;
  2369. ctx.restore();
  2370. return width;
  2371. };
  2372. // This method supposes what all custom fonts already loaded.
  2373. // If some font will be loaded after this method call, <textPath> will not be rendered correctly.
  2374. // You need to call this method manually to update glyphs cache.
  2375. this.setTextData = function (ctx) {
  2376. if (this.hasOwnProperty('glyphInfo')) return;
  2377. var that = this;
  2378. var charArr = this.getText().split('');
  2379. var spacesNumber = this.getText().split(' ').length - 1;
  2380. var dx = svg.ToNumberArray(this.parent.attribute('dx').valueOrDefault('0'));
  2381. var letterSpacing = 0;
  2382. var anchor = this.parent.style('text-anchor').valueOrDefault('start');
  2383. var thisSpacing = this.style('letter-spacing');
  2384. var parentSpacing = this.parent.style('letter-spacing');
  2385. if (!thisSpacing.hasValue() || thisSpacing.getValue() === 'inherit') {
  2386. letterSpacing = parentSpacing.toPixels();
  2387. } else if (thisSpacing.hasValue()) {
  2388. if (thisSpacing.getValue() !== 'initial' && thisSpacing.getValue() !== 'unset') {
  2389. letterSpacing = thisSpacing.toPixels();
  2390. }
  2391. }
  2392. // fill letter-spacing cache
  2393. this.letterSpacingCache = [];
  2394. for (var i = 0; i < this.getText().length; i++) {
  2395. this.letterSpacingCache.push(dx[i] !== undefined ? dx[i] : letterSpacing);
  2396. }
  2397. var dxSum = this.letterSpacingCache.reduce(function (acc, cur) { return acc + cur || 0 }, 0);
  2398. this.textWidth = this.measureText(ctx);
  2399. this.textHeight = this.fontSize();
  2400. var textFullWidth = Math.max(this.textWidth + dxSum, 0);
  2401. this.glyphInfo = [];
  2402. var fullPathWidth = this.getPathLength();
  2403. var startOffset = this.style('startOffset').numValueOrDefault(0) * fullPathWidth;
  2404. var offset = 0;
  2405. if (anchor === 'middle' || anchor === 'center') {
  2406. offset = -textFullWidth / 2;
  2407. }
  2408. if (anchor === 'end' || anchor === 'right') {
  2409. offset = -textFullWidth;
  2410. }
  2411. offset += startOffset;
  2412. var getGetterSpacingAt = function (idx) {
  2413. idx = idx || 0;
  2414. return that.letterSpacingCache[idx] || 0;
  2415. };
  2416. var findSegmentToFitChar = function (c, charI) {
  2417. var glyphWidth = that.measureText(ctx, c);
  2418. if (c === ' ' && anchor === 'justify' && textFullWidth < fullPathWidth) {
  2419. glyphWidth += (fullPathWidth - textFullWidth) / spacesNumber;
  2420. }
  2421. if (charI > -1) {
  2422. offset += getGetterSpacingAt(charI);
  2423. }
  2424. var splineStep = that.textHeight / 20;
  2425. var segment = {
  2426. p0: that.getEquidistantPointOnPath(offset, splineStep),
  2427. p1: that.getEquidistantPointOnPath(offset + glyphWidth, splineStep)
  2428. };
  2429. offset += glyphWidth;
  2430. return segment;
  2431. };
  2432. for (var i = 0; i < charArr.length; i++) {
  2433. // Find such segment what distance between p0 and p1 is approx. width of glyph
  2434. var segment = findSegmentToFitChar(charArr[i], i);
  2435. if (segment.p0 === undefined || segment.p1 === undefined) {
  2436. continue;
  2437. }
  2438. var width = that.getLineLength(segment.p0.x, segment.p0.y, segment.p1.x, segment.p1.y);
  2439. // Note: Since glyphs are rendered one at a time, any kerning pair data built into the font will not be used.
  2440. // Can foresee having a rough pair table built in that the developer can override as needed.
  2441. // Or use "dx" attribute of the <text> node as a naive replacement
  2442. var kern = 0;
  2443. // placeholder for future implementation
  2444. var midpoint = that.getPointOnLine(kern + width / 2.0, segment.p0.x, segment.p0.y, segment.p1.x, segment.p1.y);
  2445. var rotation = Math.atan2((segment.p1.y - segment.p0.y), (segment.p1.x - segment.p0.x));
  2446. this.glyphInfo.push({
  2447. transposeX: midpoint.x,
  2448. transposeY: midpoint.y,
  2449. text: charArr[i],
  2450. rotation: rotation,
  2451. p0: segment.p0,
  2452. p1: segment.p1
  2453. });
  2454. }
  2455. };
  2456. this.parsePathData = function (path) {
  2457. this.pathLength = undefined; // reset path length
  2458. if (!path) {
  2459. return [];
  2460. }
  2461. var ca = [];
  2462. var pp = path.PathParser;
  2463. pp.reset();
  2464. // convert l, H, h, V, and v to L
  2465. while (!pp.isEnd()) {
  2466. var points = [];
  2467. var cmd = null;
  2468. var startX = pp.current ? pp.current.x : 0;
  2469. var startY = pp.current ? pp.current.y : 0;
  2470. pp.nextCommand();
  2471. var C = pp.command.toUpperCase();
  2472. switch (pp.command) {
  2473. case 'M':
  2474. case 'm':
  2475. var p = pp.getAsCurrentPoint();
  2476. // pp.addMarker(p);
  2477. points.push(p.x, p.y);
  2478. pp.start = pp.current;
  2479. while (!pp.isCommandOrEnd()) {
  2480. var p = pp.getAsCurrentPoint();
  2481. points.push(p.x, p.y);
  2482. cmd = 'L';
  2483. }
  2484. break;
  2485. case 'L':
  2486. case 'l':
  2487. while (!pp.isCommandOrEnd()) {
  2488. var p = pp.getAsCurrentPoint();
  2489. points.push(p.x, p.y);
  2490. }
  2491. cmd = 'L';
  2492. break;
  2493. case 'H':
  2494. case 'h':
  2495. while (!pp.isCommandOrEnd()) {
  2496. var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(),
  2497. pp.current.y);
  2498. points.push(newP.x, newP.y);
  2499. pp.current = newP;
  2500. }
  2501. cmd = 'L';
  2502. break;
  2503. case 'V':
  2504. case 'v':
  2505. while (!pp.isCommandOrEnd()) {
  2506. var newP = new svg.Point(pp.current.x,
  2507. (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
  2508. points.push(newP.x, newP.y);
  2509. pp.current = newP;
  2510. }
  2511. cmd = 'L';
  2512. break;
  2513. case 'C':
  2514. case 'c':
  2515. while (!pp.isCommandOrEnd()) {
  2516. var p1 = pp.getPoint();
  2517. var cntrl = pp.getAsControlPoint();
  2518. var cp = pp.getAsCurrentPoint();
  2519. points.push(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  2520. }
  2521. break;
  2522. case 'S':
  2523. case 's':
  2524. while (!pp.isCommandOrEnd()) {
  2525. var p1 = pp.getReflectedControlPoint();
  2526. var cntrl = pp.getAsControlPoint();
  2527. var cp = pp.getAsCurrentPoint();
  2528. points.push(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  2529. }
  2530. cmd = 'C';
  2531. break;
  2532. case 'Q':
  2533. case 'q':
  2534. while (!pp.isCommandOrEnd()) {
  2535. var cntrl = pp.getAsControlPoint();
  2536. var cp = pp.getAsCurrentPoint();
  2537. points.push(cntrl.x, cntrl.y, cp.x, cp.y);
  2538. }
  2539. break;
  2540. case 'T':
  2541. case 't':
  2542. while (!pp.isCommandOrEnd()) {
  2543. var cntrl = pp.getReflectedControlPoint();
  2544. pp.control = cntrl;
  2545. var cp = pp.getAsCurrentPoint();
  2546. points.push(cntrl.x, cntrl.y, cp.x, cp.y);
  2547. }
  2548. cmd = 'Q';
  2549. break;
  2550. case 'A':
  2551. case 'a':
  2552. while (!pp.isCommandOrEnd()) {
  2553. var curr = pp.current; // x1, y1
  2554. var rx = pp.getScalar();
  2555. var ry = pp.getScalar();
  2556. var xAxisRotation = pp.getScalar() * (Math.PI / 180.0); // ¦Õ
  2557. var largeArcFlag = pp.getScalar(); // fA
  2558. var sweepFlag = pp.getScalar(); // fS
  2559. var cp = pp.getAsCurrentPoint(); // x2, y2
  2560. // Conversion from endpoint to center parameterization
  2561. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  2562. // x1', y1'
  2563. var currp = new svg.Point(
  2564. Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,
  2565. -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
  2566. );
  2567. // adjust radii
  2568. var l = Math.pow(currp.x, 2) / Math.pow(rx, 2) + Math.pow(currp.y, 2) / Math.pow(ry, 2);
  2569. if (l > 1) {
  2570. rx *= Math.sqrt(l);
  2571. ry *= Math.sqrt(l);
  2572. }
  2573. // cx', cy'
  2574. var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
  2575. ((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))) /
  2576. (Math.pow(rx, 2) * Math.pow(currp.y, 2) + Math.pow(ry, 2) * Math.pow(currp.x, 2))
  2577. );
  2578. if (isNaN(s)) s = 0;
  2579. var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
  2580. // cx, cy
  2581. var centp = new svg.Point(
  2582. (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
  2583. (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
  2584. );
  2585. // vector magnitude
  2586. var m = function (v) {
  2587. return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2));
  2588. };
  2589. // ratio between two vectors
  2590. var r = function (u, v) {
  2591. return (u[0] * v[0] + u[1] * v[1]) / (m(u) * m(v))
  2592. };
  2593. // angle between two vectors
  2594. var a = function (u, v) {
  2595. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(r(u, v));
  2596. };
  2597. // initial angle
  2598. var a1 = a([1, 0], [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]); // ¦È1
  2599. // angle delta
  2600. var u = [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry];
  2601. var v = [(-currp.x - cpp.x) / rx, (-currp.y - cpp.y) / ry];
  2602. var ad = a(u, v); // ¦¤¦È
  2603. if (r(u, v) <= -1) ad = Math.PI;
  2604. if (r(u, v) >= 1) ad = 0;
  2605. if (sweepFlag === 0 && ad > 0) ad = ad - 2 * Math.PI;
  2606. if (sweepFlag === 1 && ad < 0) ad = ad + 2 * Math.PI;
  2607. points = [centp.x, centp.y, rx, ry, a1, ad, xAxisRotation, sweepFlag];
  2608. }
  2609. break;
  2610. case 'Z':
  2611. case 'z':
  2612. pp.current = pp.start;
  2613. }
  2614. if (C !== 'Z') {
  2615. ca.push({
  2616. command: cmd || C,
  2617. points: points,
  2618. start: {
  2619. x: startX,
  2620. y: startY
  2621. },
  2622. pathLength: this.calcLength(startX, startY, cmd || C, points)
  2623. });
  2624. } else {
  2625. ca.push({
  2626. command: 'z',
  2627. points: [],
  2628. start: undefined,
  2629. pathLength: 0
  2630. });
  2631. }
  2632. }
  2633. return ca;
  2634. };
  2635. this.getPathLength = function () {
  2636. if (this.pathLength === undefined || this.pathLength === null || isNaN(this.pathLength)) {
  2637. this.pathLength = 0;
  2638. for (var l = 0; l < this.dataArray.length; l++) {
  2639. if (this.dataArray[l].pathLength > 0) {
  2640. this.pathLength += this.dataArray[l].pathLength;
  2641. }
  2642. }
  2643. }
  2644. return this.pathLength;
  2645. };
  2646. this.getPointOnPath = function (distance) {
  2647. var cumulativePathLength = 0;
  2648. var fullLen = this.getPathLength();
  2649. var p = undefined;
  2650. if (distance < -0.00005 || distance - 0.00005 > fullLen) return undefined;
  2651. for (var i = 0; i < this.dataArray.length; i++) {
  2652. var pathCmd = this.dataArray[i];
  2653. if (pathCmd
  2654. && (
  2655. pathCmd.pathLength < 0.00005
  2656. || cumulativePathLength + pathCmd.pathLength + 0.00005 < distance
  2657. )
  2658. ) {
  2659. cumulativePathLength += pathCmd.pathLength;
  2660. continue;
  2661. }
  2662. var delta = distance - cumulativePathLength;
  2663. var currentT = undefined;
  2664. switch (pathCmd.command) {
  2665. case 'L':
  2666. p = this.getPointOnLine(delta, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.start.x, pathCmd.start.y);
  2667. break;
  2668. case 'A':
  2669. var start = pathCmd.points[4];
  2670. // 4 = theta
  2671. var dTheta = pathCmd.points[5];
  2672. // 5 = dTheta
  2673. var end = pathCmd.points[4] + dTheta;
  2674. currentT = start + delta / pathCmd.pathLength * dTheta;
  2675. if (dTheta < 0 && currentT < end || dTheta >= 0 && currentT > end) {
  2676. break;
  2677. }
  2678. p = this.getPointOnEllipticalArc(pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], currentT, pathCmd.points[6]);
  2679. break;
  2680. case 'C':
  2681. currentT = delta / pathCmd.pathLength;
  2682. if (currentT > 1) {
  2683. currentT = 1;
  2684. }
  2685. p = this.getPointOnCubicBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], pathCmd.points[4], pathCmd.points[5]);
  2686. break;
  2687. case 'Q':
  2688. currentT = delta / pathCmd.pathLength;
  2689. if (currentT > 1) {
  2690. currentT = 1;
  2691. }
  2692. p = this.getPointOnQuadraticBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3]);
  2693. break;
  2694. }
  2695. if (p !== undefined && p !== {}) {
  2696. return p;
  2697. }
  2698. break;
  2699. }
  2700. };
  2701. // TODO need some optimisations. possibly build cache only for curved segments?
  2702. this.buildEquidistantCache = function (step, precision) {
  2703. var fullLen = this.getPathLength();
  2704. precision = precision || 0.25; // accuracy vs performance
  2705. step = step || fullLen / 100;
  2706. this.equidistantCache = this.equidistantCache || {};
  2707. if (
  2708. !this.equidistantCache.hasOwnProperty('points')
  2709. || this.equidistantCache.step != step
  2710. || this.equidistantCache.precision != precision
  2711. ) {
  2712. // Prepare cache
  2713. this.equidistantCache = {
  2714. step: step,
  2715. precision: precision,
  2716. points: []
  2717. };
  2718. // Calculate points
  2719. var s = 0;
  2720. for (var l = 0; l <= fullLen; l += precision) {
  2721. var p0 = this.getPointOnPath(l),
  2722. p1 = this.getPointOnPath(l + precision);
  2723. if (p0 === undefined || p1 === undefined) continue;
  2724. s += this.getLineLength(p0.x, p0.y, p1.x, p1.y);
  2725. if (s >= step) {
  2726. this.equidistantCache.points.push({
  2727. x: p0.x,
  2728. y: p0.y,
  2729. distance: l
  2730. });
  2731. s -= step;
  2732. }
  2733. }
  2734. }
  2735. };
  2736. this.getEquidistantPointOnPath = function (targetDistance, step, precision) {
  2737. this.buildEquidistantCache(step, precision);
  2738. if (targetDistance < 0 || targetDistance - this.getPathLength() > 0.00005) return undefined;
  2739. var idx = Math.round(targetDistance / this.getPathLength() * (this.equidistantCache.points.length - 1));
  2740. return this.equidistantCache.points[idx] || undefined;
  2741. };
  2742. this.getLineLength = function (x1, y1, x2, y2) {
  2743. return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  2744. };
  2745. this.getPointOnLine = function (dist, P1x, P1y, P2x, P2y, fromX, fromY) {
  2746. if (fromX === undefined) {
  2747. fromX = P1x;
  2748. }
  2749. if (fromY === undefined) {
  2750. fromY = P1y;
  2751. }
  2752. var m = (P2y - P1y) / ((P2x - P1x) + 0.00000001);
  2753. var run = Math.sqrt(dist * dist / (1 + m * m));
  2754. if (P2x < P1x) {
  2755. run *= -1;
  2756. }
  2757. var rise = m * run;
  2758. var pt;
  2759. if (P2x === P1x) { // vertical line
  2760. pt = {
  2761. x: fromX,
  2762. y: fromY + rise
  2763. };
  2764. } else if ((fromY - P1y) / ((fromX - P1x) + 0.00000001) === m) {
  2765. pt = {
  2766. x: fromX + run,
  2767. y: fromY + rise
  2768. };
  2769. }
  2770. else {
  2771. var ix, iy;
  2772. var len = this.getLineLength(P1x, P1y, P2x, P2y);
  2773. if (len < 0.00000001) {
  2774. return undefined;
  2775. }
  2776. var u = (((fromX - P1x) * (P2x - P1x)) + ((fromY - P1y) * (P2y - P1y)));
  2777. u = u / (len * len);
  2778. ix = P1x + u * (P2x - P1x);
  2779. iy = P1y + u * (P2y - P1y);
  2780. var pRise = this.getLineLength(fromX, fromY, ix, iy);
  2781. var pRun = Math.sqrt(dist * dist - pRise * pRise);
  2782. run = Math.sqrt(pRun * pRun / (1 + m * m));
  2783. if (P2x < P1x) {
  2784. run *= -1;
  2785. }
  2786. rise = m * run;
  2787. pt = {
  2788. x: ix + run,
  2789. y: iy + rise
  2790. };
  2791. }
  2792. return pt;
  2793. };
  2794. this.getPointOnCubicBezier = function (pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) {
  2795. function CB1(t) {
  2796. return t * t * t;
  2797. }
  2798. function CB2(t) {
  2799. return 3 * t * t * (1 - t);
  2800. }
  2801. function CB3(t) {
  2802. return 3 * t * (1 - t) * (1 - t);
  2803. }
  2804. function CB4(t) {
  2805. return (1 - t) * (1 - t) * (1 - t);
  2806. }
  2807. var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct);
  2808. var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct);
  2809. return {
  2810. x: x,
  2811. y: y
  2812. };
  2813. };
  2814. this.getPointOnQuadraticBezier = function (pct, P1x, P1y, P2x, P2y, P3x, P3y) {
  2815. function QB1(t) {
  2816. return t * t;
  2817. }
  2818. function QB2(t) {
  2819. return 2 * t * (1 - t);
  2820. }
  2821. function QB3(t) {
  2822. return (1 - t) * (1 - t);
  2823. }
  2824. var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct);
  2825. var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct);
  2826. return {
  2827. x: x,
  2828. y: y
  2829. };
  2830. };
  2831. this.getPointOnEllipticalArc = function (cx, cy, rx, ry, theta, psi) {
  2832. var cosPsi = Math.cos(psi), sinPsi = Math.sin(psi);
  2833. var pt = {
  2834. x: rx * Math.cos(theta),
  2835. y: ry * Math.sin(theta)
  2836. };
  2837. return {
  2838. x: cx + (pt.x * cosPsi - pt.y * sinPsi),
  2839. y: cy + (pt.x * sinPsi + pt.y * cosPsi)
  2840. };
  2841. };
  2842. this.calcLength = function (x, y, cmd, points) {
  2843. var len, p1, p2, t;
  2844. switch (cmd) {
  2845. case 'L':
  2846. return this.getLineLength(x, y, points[0], points[1]);
  2847. case 'C':
  2848. // Approximates by breaking curve into 100 line segments
  2849. len = 0.0;
  2850. p1 = this.getPointOnCubicBezier(0, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
  2851. for (t = 0.01; t <= 1; t += 0.01) {
  2852. p2 = this.getPointOnCubicBezier(t, x, y, points[0], points[1], points[2], points[3], points[4], points[5]);
  2853. len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
  2854. p1 = p2;
  2855. }
  2856. return len;
  2857. case 'Q':
  2858. // Approximates by breaking curve into 100 line segments
  2859. len = 0.0;
  2860. p1 = this.getPointOnQuadraticBezier(0, x, y, points[0], points[1], points[2], points[3]);
  2861. for (t = 0.01; t <= 1; t += 0.01) {
  2862. p2 = this.getPointOnQuadraticBezier(t, x, y, points[0], points[1], points[2], points[3]);
  2863. len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
  2864. p1 = p2;
  2865. }
  2866. return len;
  2867. case 'A':
  2868. // Approximates by breaking curve into line segments
  2869. len = 0.0;
  2870. var start = points[4];
  2871. // 4 = theta
  2872. var dTheta = points[5];
  2873. // 5 = dTheta
  2874. var end = points[4] + dTheta;
  2875. var inc = Math.PI / 180.0;
  2876. // 1 degree resolution
  2877. if (Math.abs(start - end) < inc) {
  2878. inc = Math.abs(start - end);
  2879. }
  2880. // Note: for purpose of calculating arc length, not going to worry about rotating X-axis by angle psi
  2881. p1 = this.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], start, 0);
  2882. if (dTheta < 0) {// clockwise
  2883. for (t = start - inc; t > end; t -= inc) {
  2884. p2 = this.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
  2885. len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
  2886. p1 = p2;
  2887. }
  2888. }
  2889. else {// counter-clockwise
  2890. for (t = start + inc; t < end; t += inc) {
  2891. p2 = this.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0);
  2892. len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
  2893. p1 = p2;
  2894. }
  2895. }
  2896. p2 = this.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], end, 0);
  2897. len += this.getLineLength(p1.x, p1.y, p2.x, p2.y);
  2898. return len;
  2899. }
  2900. return 0;
  2901. };
  2902. this.dataArray = this.parsePathData(pathElement);
  2903. };
  2904. svg.Element.textPath.prototype = new svg.Element.TextElementBase;
  2905. // image element
  2906. svg.Element.image = function (node) {
  2907. this.base = svg.Element.RenderedElementBase;
  2908. this.base(node);
  2909. var href = this.getHrefAttribute().value;
  2910. if (href == '') { return; }
  2911. var isSvg = href.match(/\.svg$/);
  2912. svg.Images.push(this);
  2913. this.loaded = false;
  2914. if (!isSvg) {
  2915. this.img = doc.createElement('img');
  2916. if (svg.opts['useCORS'] == true) { this.img.crossOrigin = 'Anonymous'; }
  2917. var self = this;
  2918. this.img.onload = function () { self.loaded = true; };
  2919. this.img.onerror = function () {
  2920. svg.log('ERROR: image "' + href + '" not found');
  2921. self.loaded = true;
  2922. };
  2923. this.img.src = href;
  2924. } else {
  2925. this.img = svg.ajax(href);
  2926. this.loaded = true;
  2927. }
  2928. this.renderChildren = function (ctx) {
  2929. var x = this.attribute('x').toPixels('x');
  2930. var y = this.attribute('y').toPixels('y');
  2931. var width = this.attribute('width').toPixels('x');
  2932. var height = this.attribute('height').toPixels('y');
  2933. if (width == 0 || height == 0) return;
  2934. ctx.save();
  2935. if (isSvg) {
  2936. ctx.drawSvg(this.img, x, y, width, height);
  2937. } else {
  2938. ctx.translate(x, y);
  2939. svg.AspectRatio(ctx,
  2940. this.attribute('preserveAspectRatio').value,
  2941. width,
  2942. this.img.width,
  2943. height,
  2944. this.img.height,
  2945. 0,
  2946. 0);
  2947. if (self.loaded) {
  2948. if (this.img.complete === undefined || this.img.complete) {
  2949. ctx.drawImage(this.img, 0, 0);
  2950. }
  2951. }
  2952. }
  2953. ctx.restore();
  2954. };
  2955. this.getBoundingBox = function () {
  2956. var x = this.attribute('x').toPixels('x');
  2957. var y = this.attribute('y').toPixels('y');
  2958. var width = this.attribute('width').toPixels('x');
  2959. var height = this.attribute('height').toPixels('y');
  2960. return new svg.BoundingBox(x, y, x + width, y + height);
  2961. };
  2962. };
  2963. svg.Element.image.prototype = new svg.Element.RenderedElementBase;
  2964. // group element
  2965. svg.Element.g = function (node) {
  2966. this.base = svg.Element.RenderedElementBase;
  2967. this.base(node);
  2968. this.getBoundingBox = function (ctx) {
  2969. var bb = new svg.BoundingBox();
  2970. for (var i = 0; i < this.children.length; i++) {
  2971. bb.addBoundingBox(this.children[i].getBoundingBox(ctx));
  2972. }
  2973. return bb;
  2974. };
  2975. };
  2976. svg.Element.g.prototype = new svg.Element.RenderedElementBase;
  2977. // symbol element
  2978. svg.Element.symbol = function (node) {
  2979. this.base = svg.Element.RenderedElementBase;
  2980. this.base(node);
  2981. this.render = function (/* ctx */) {
  2982. // NO RENDER
  2983. };
  2984. };
  2985. svg.Element.symbol.prototype = new svg.Element.RenderedElementBase;
  2986. svg.ParseExternalUrl = function (url) {
  2987. // single quotes [2]
  2988. // v double quotes [3]
  2989. // v v no quotes [4]
  2990. // v v v
  2991. var urlMatch = url.match(/url\(('([^']+)'|"([^"]+)"|([^'"\)]+))\)/) || [];
  2992. return urlMatch[2] || urlMatch[3] || urlMatch[4];
  2993. };
  2994. // style element
  2995. svg.Element.style = function (node) {
  2996. this.base = svg.Element.ElementBase;
  2997. this.base(node);
  2998. // text, or spaces then CDATA
  2999. var css = '';
  3000. for (var i = 0; i < node.childNodes.length; i++) {
  3001. css += node.childNodes[i].data;
  3002. }
  3003. css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(^[\s]*\/\/.*)/gm, ''); // remove comments
  3004. css = svg.compressSpaces(css); // replace whitespace
  3005. var cssDefs = css.split('}');
  3006. for (var i = 0; i < cssDefs.length; i++) {
  3007. if (svg.trim(cssDefs[i]) != '') {
  3008. var cssDef = cssDefs[i].split('{');
  3009. var cssClasses = cssDef[0].split(',');
  3010. var cssProps = cssDef[1].split(';');
  3011. for (var j = 0; j < cssClasses.length; j++) {
  3012. var cssClass = svg.trim(cssClasses[j]);
  3013. if (cssClass != '') {
  3014. var props = svg.Styles[cssClass] || {};
  3015. for (var k = 0; k < cssProps.length; k++) {
  3016. var prop = cssProps[k].indexOf(':');
  3017. var name = cssProps[k].substr(0, prop);
  3018. var value = cssProps[k].substr(prop + 1, cssProps[k].length - prop);
  3019. if (name != null && value != null) {
  3020. props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value));
  3021. }
  3022. }
  3023. svg.Styles[cssClass] = props;
  3024. svg.StylesSpecificity[cssClass] = getSelectorSpecificity(cssClass);
  3025. if (cssClass == '@font-face' && !nodeEnv) {
  3026. var fontFamily = props['font-family'].value.replace(/"/g, '');
  3027. var srcs = props['src'].value.split(',');
  3028. for (var s = 0; s < srcs.length; s++) {
  3029. if (srcs[s].indexOf('format("svg")') > 0) {
  3030. var url = svg.ParseExternalUrl(srcs[s]);
  3031. if (url) {
  3032. var doc = svg.parseXml(svg.ajax(url));
  3033. var fonts = doc.getElementsByTagName('font');
  3034. for (var f = 0; f < fonts.length; f++) {
  3035. var font = svg.CreateElement(fonts[f]);
  3036. svg.Definitions[fontFamily] = font;
  3037. }
  3038. }
  3039. }
  3040. }
  3041. }
  3042. }
  3043. }
  3044. }
  3045. }
  3046. };
  3047. svg.Element.style.prototype = new svg.Element.ElementBase;
  3048. // use element
  3049. svg.Element.use = function (node) {
  3050. this.base = svg.Element.RenderedElementBase;
  3051. this.base(node);
  3052. this.baseSetContext = this.setContext;
  3053. this.setContext = function (ctx) {
  3054. this.baseSetContext(ctx);
  3055. if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').toPixels('x'), 0);
  3056. if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').toPixels('y'));
  3057. };
  3058. var element = this.getHrefAttribute().getDefinition();
  3059. this.path = function (ctx) {
  3060. if (element != null) element.path(ctx);
  3061. };
  3062. this.elementTransform = function () {
  3063. if (element != null && element.style('transform', false, true).hasValue()) {
  3064. return new svg.Transform(element.style('transform', false, true).value);
  3065. }
  3066. };
  3067. this.getBoundingBox = function (ctx) {
  3068. if (element != null) return element.getBoundingBox(ctx);
  3069. };
  3070. this.renderChildren = function (ctx) {
  3071. if (element != null) {
  3072. var tempSvg = element;
  3073. if (element.type == 'symbol') {
  3074. // render me using a temporary svg element in symbol cases (http://www.w3.org/TR/SVG/struct.html#UseElement)
  3075. tempSvg = new svg.Element.svg();
  3076. tempSvg.type = 'svg';
  3077. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', element.attribute('viewBox').value);
  3078. tempSvg.attributes['preserveAspectRatio'] = new svg.Property('preserveAspectRatio', element.attribute('preserveAspectRatio').value);
  3079. tempSvg.attributes['overflow'] = new svg.Property('overflow', element.attribute('overflow').value);
  3080. tempSvg.children = element.children;
  3081. }
  3082. if (tempSvg.type == 'svg') {
  3083. // if symbol or svg, inherit width/height from me
  3084. if (this.attribute('width').hasValue()) tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);
  3085. if (this.attribute('height').hasValue()) tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);
  3086. }
  3087. var oldParent = tempSvg.parent;
  3088. tempSvg.parent = null;
  3089. tempSvg.render(ctx);
  3090. tempSvg.parent = oldParent;
  3091. }
  3092. };
  3093. };
  3094. svg.Element.use.prototype = new svg.Element.RenderedElementBase;
  3095. // mask element
  3096. svg.Element.mask = function (node) {
  3097. this.base = svg.Element.ElementBase;
  3098. this.base(node);
  3099. this.apply = function (ctx, element) {
  3100. // render as temp svg
  3101. var x = this.attribute('x').toPixels('x');
  3102. var y = this.attribute('y').toPixels('y');
  3103. var width = this.attribute('width').toPixels('x');
  3104. var height = this.attribute('height').toPixels('y');
  3105. if (width == 0 && height == 0) {
  3106. var bb = new svg.BoundingBox();
  3107. for (var i = 0; i < this.children.length; i++) {
  3108. bb.addBoundingBox(this.children[i].getBoundingBox(ctx));
  3109. }
  3110. var x = Math.floor(bb.x1);
  3111. var y = Math.floor(bb.y1);
  3112. var width = Math.floor(bb.width());
  3113. var height = Math.floor(bb.height());
  3114. }
  3115. // temporarily remove mask to avoid recursion
  3116. var mask = element.style('mask').value;
  3117. element.style('mask').value = '';
  3118. var cMask = createCanvas(x + width, y + height);
  3119. var maskCtx = cMask.getContext('2d');
  3120. svg.SetDefaults(maskCtx);
  3121. this.renderChildren(maskCtx);
  3122. // convert mask to alpha with a fake node
  3123. // TODO: refactor out apply from feColorMatrix
  3124. var cm = new svg.Element.feColorMatrix({
  3125. nodeType: 1,
  3126. childNodes: [],
  3127. attributes: [
  3128. { nodeName: 'type', value: 'luminanceToAlpha' },
  3129. { nodeName: 'includeOpacity', value: 'true' },
  3130. ]
  3131. });
  3132. cm.apply(maskCtx, 0, 0, x + width, y + height);
  3133. var c = createCanvas(x + width, y + height);
  3134. var tempCtx = c.getContext('2d');
  3135. svg.SetDefaults(tempCtx);
  3136. element.render(tempCtx);
  3137. tempCtx.globalCompositeOperation = 'destination-in';
  3138. tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat');
  3139. tempCtx.fillRect(0, 0, x + width, y + height);
  3140. ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat');
  3141. ctx.fillRect(0, 0, x + width, y + height);
  3142. // reassign mask
  3143. element.style('mask').value = mask;
  3144. };
  3145. this.render = function (/* ctx */) {
  3146. // NO RENDER
  3147. };
  3148. };
  3149. svg.Element.mask.prototype = new svg.Element.ElementBase;
  3150. // clip element
  3151. svg.Element.clipPath = function (node) {
  3152. this.base = svg.Element.ElementBase;
  3153. this.base(node);
  3154. this.apply = function (ctx) {
  3155. var hasContext2D = (typeof CanvasRenderingContext2D !== 'undefined');
  3156. var oldBeginPath = ctx.beginPath;
  3157. var oldClosePath = ctx.closePath;
  3158. if (hasContext2D) {
  3159. CanvasRenderingContext2D.prototype.beginPath = function () { };
  3160. CanvasRenderingContext2D.prototype.closePath = function () { };
  3161. }
  3162. oldBeginPath.call(ctx);
  3163. for (var i = 0; i < this.children.length; i++) {
  3164. var child = this.children[i];
  3165. if (typeof child.path != 'undefined') {
  3166. var transform = typeof child.elementTransform != 'undefined' && child.elementTransform(); // handle <use />
  3167. if (!transform && child.style('transform', false, true).hasValue()) {
  3168. transform = new svg.Transform(child.style('transform', false, true).value);
  3169. }
  3170. if (transform) {
  3171. transform.apply(ctx);
  3172. }
  3173. child.path(ctx);
  3174. if (hasContext2D) {
  3175. CanvasRenderingContext2D.prototype.closePath = oldClosePath;
  3176. }
  3177. if (transform) { transform.unapply(ctx); }
  3178. }
  3179. }
  3180. oldClosePath.call(ctx);
  3181. ctx.clip();
  3182. if (hasContext2D) {
  3183. CanvasRenderingContext2D.prototype.beginPath = oldBeginPath;
  3184. CanvasRenderingContext2D.prototype.closePath = oldClosePath;
  3185. }
  3186. };
  3187. this.render = function (/* ctx */) {
  3188. // NO RENDER
  3189. };
  3190. };
  3191. svg.Element.clipPath.prototype = new svg.Element.ElementBase;
  3192. // filters
  3193. svg.Element.filter = function (node) {
  3194. this.base = svg.Element.ElementBase;
  3195. this.base(node);
  3196. this.apply = function (ctx, element) {
  3197. // render as temp svg
  3198. var bb = element.getBoundingBox(ctx);
  3199. var x = Math.floor(bb.x1);
  3200. var y = Math.floor(bb.y1);
  3201. var width = Math.floor(bb.width());
  3202. var height = Math.floor(bb.height());
  3203. // temporarily remove filter to avoid recursion
  3204. var filter = element.style('filter').value;
  3205. element.style('filter').value = '';
  3206. var px = 0,
  3207. py = 0;
  3208. for (var i = 0; i < this.children.length; i++) {
  3209. var efd = this.children[i].extraFilterDistance || 0;
  3210. px = Math.max(px, efd);
  3211. py = Math.max(py, efd);
  3212. }
  3213. var c = createCanvas(width + 2 * px, height + 2 * py);
  3214. var tempCtx = c.getContext('2d');
  3215. svg.SetDefaults(tempCtx);
  3216. tempCtx.translate(-x + px, -y + py);
  3217. element.render(tempCtx);
  3218. // apply filters
  3219. for (var i = 0; i < this.children.length; i++) {
  3220. if (typeof this.children[i].apply == 'function') {
  3221. this.children[i].apply(tempCtx, 0, 0, width + 2 * px, height + 2 * py);
  3222. }
  3223. }
  3224. // render on me
  3225. ctx.drawImage(c, 0, 0, width + 2 * px, height + 2 * py, x - px, y - py, width + 2 * px, height + 2 * py);
  3226. // reassign filter
  3227. element.style('filter', true).value = filter;
  3228. };
  3229. this.render = function (/* ctx */) {
  3230. // NO RENDER
  3231. };
  3232. };
  3233. svg.Element.filter.prototype = new svg.Element.ElementBase;
  3234. svg.Element.feDropShadow = function (node) {
  3235. this.base = svg.Element.ElementBase;
  3236. this.base(node);
  3237. this.addStylesFromStyleDefinition();
  3238. this.apply = function (/* ctx, x, y, width, height */) {
  3239. // TODO: implement
  3240. };
  3241. };
  3242. svg.Element.feDropShadow.prototype = new svg.Element.ElementBase;
  3243. svg.Element.feMorphology = function (node) {
  3244. this.base = svg.Element.ElementBase;
  3245. this.base(node);
  3246. this.apply = function (/* ctx, x, y, width, height */) {
  3247. // TODO: implement
  3248. };
  3249. };
  3250. svg.Element.feMorphology.prototype = new svg.Element.ElementBase;
  3251. svg.Element.feComposite = function (node) {
  3252. this.base = svg.Element.ElementBase;
  3253. this.base(node);
  3254. this.apply = function (/* ctx, x, y, width, height */) {
  3255. // TODO: implement
  3256. };
  3257. };
  3258. svg.Element.feComposite.prototype = new svg.Element.ElementBase;
  3259. svg.Element.feColorMatrix = function (node) {
  3260. this.base = svg.Element.ElementBase;
  3261. this.base(node);
  3262. var matrix = svg.ToNumberArray(this.attribute('values').value);
  3263. switch (this.attribute('type').valueOrDefault('matrix')) { // http://www.w3.org/TR/SVG/filters.html#feColorMatrixElement
  3264. case 'saturate':
  3265. var s = matrix[0];
  3266. matrix = [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0, 0,
  3267. 0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0, 0,
  3268. 0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0, 0,
  3269. 0, 0, 0, 1, 0,
  3270. 0, 0, 0, 0, 1
  3271. ];
  3272. break;
  3273. case 'hueRotate':
  3274. var a = matrix[0] * Math.PI / 180.0;
  3275. var c = function (m1, m2, m3) { return m1 + Math.cos(a) * m2 + Math.sin(a) * m3; };
  3276. matrix = [c(0.213, 0.787, -0.213), c(0.715, -0.715, -0.715), c(0.072, -0.072, 0.928), 0, 0,
  3277. c(0.213, -0.213, 0.143), c(0.715, 0.285, 0.140), c(0.072, -0.072, -0.283), 0, 0,
  3278. c(0.213, -0.213, -0.787), c(0.715, -0.715, 0.715), c(0.072, 0.928, 0.072), 0, 0,
  3279. 0, 0, 0, 1, 0,
  3280. 0, 0, 0, 0, 1
  3281. ];
  3282. break;
  3283. case 'luminanceToAlpha':
  3284. matrix = [0, 0, 0, 0, 0,
  3285. 0, 0, 0, 0, 0,
  3286. 0, 0, 0, 0, 0,
  3287. 0.2125, 0.7154, 0.0721, 0, 0,
  3288. 0, 0, 0, 0, 1
  3289. ];
  3290. break;
  3291. }
  3292. function imGet(img, x, y, width, height, rgba) {
  3293. return img[y * width * 4 + x * 4 + rgba];
  3294. }
  3295. function imSet(img, x, y, width, height, rgba, val) {
  3296. img[y * width * 4 + x * 4 + rgba] = val;
  3297. }
  3298. function m(i, v) {
  3299. var mi = matrix[i];
  3300. return mi * (mi < 0 ? v - 255 : v);
  3301. }
  3302. var includeOpacity = this.attribute('includeOpacity').hasValue();
  3303. this.apply = function (ctx, x, y, width, height) {
  3304. // assuming x==0 && y==0 for now
  3305. var srcData = ctx.getImageData(0, 0, width, height);
  3306. for (var y = 0; y < height; y++) {
  3307. for (var x = 0; x < width; x++) {
  3308. var r = imGet(srcData.data, x, y, width, height, 0);
  3309. var g = imGet(srcData.data, x, y, width, height, 1);
  3310. var b = imGet(srcData.data, x, y, width, height, 2);
  3311. var a = imGet(srcData.data, x, y, width, height, 3);
  3312. var nr = m(0, r) + m(1, g) + m(2, b) + m(3, a) + m(4, 1);
  3313. var ng = m(5, r) + m(6, g) + m(7, b) + m(8, a) + m(9, 1);
  3314. var nb = m(10, r) + m(11, g) + m(12, b) + m(13, a) + m(14, 1);
  3315. var na = m(15, r) + m(16, g) + m(17, b) + m(18, a) + m(19, 1);
  3316. if (includeOpacity) {
  3317. nr = ng = nb = 0;
  3318. na *= a / 255;
  3319. }
  3320. imSet(srcData.data, x, y, width, height, 0, nr);
  3321. imSet(srcData.data, x, y, width, height, 1, ng);
  3322. imSet(srcData.data, x, y, width, height, 2, nb);
  3323. imSet(srcData.data, x, y, width, height, 3, na);
  3324. }
  3325. }
  3326. ctx.clearRect(0, 0, width, height);
  3327. ctx.putImageData(srcData, 0, 0);
  3328. };
  3329. };
  3330. svg.Element.feColorMatrix.prototype = new svg.Element.ElementBase;
  3331. svg.Element.feGaussianBlur = function (node) {
  3332. this.base = svg.Element.ElementBase;
  3333. this.base(node);
  3334. this.blurRadius = Math.floor(this.attribute('stdDeviation').numValue());
  3335. this.extraFilterDistance = this.blurRadius;
  3336. this.apply = function (ctx, x, y, width, height) {
  3337. if (!stackblurCanvas || typeof stackblurCanvas.canvasRGBA === 'undefined') {
  3338. svg.log('ERROR: StackBlur.js must be included for blur to work');
  3339. return;
  3340. }
  3341. // StackBlur requires canvas be on document
  3342. ctx.canvas.id = svg.UniqueId();
  3343. {
  3344. ctx.canvas.style.display = 'none';
  3345. doc.body.appendChild(ctx.canvas);
  3346. }
  3347. stackblurCanvas.canvasRGBA(ctx.canvas, x, y, width, height, this.blurRadius);
  3348. {
  3349. doc.body.removeChild(ctx.canvas);
  3350. }
  3351. };
  3352. };
  3353. svg.Element.feGaussianBlur.prototype = new svg.Element.ElementBase;
  3354. // title element, do nothing
  3355. svg.Element.title = function (/* node */) { };
  3356. svg.Element.title.prototype = new svg.Element.ElementBase;
  3357. // desc element, do nothing
  3358. svg.Element.desc = function (/* node */) { };
  3359. svg.Element.desc.prototype = new svg.Element.ElementBase;
  3360. svg.Element.MISSING = function (node) {
  3361. svg.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.');
  3362. };
  3363. svg.Element.MISSING.prototype = new svg.Element.ElementBase;
  3364. // element factory
  3365. svg.CreateElement = function (node) {
  3366. var className = node.nodeName.replace(/^[^:]+:/, ''); // remove namespace
  3367. className = className.replace(/\-/g, ''); // remove dashes
  3368. var e = null;
  3369. if (typeof svg.Element[className] != 'undefined') {
  3370. e = new svg.Element[className](node);
  3371. } else {
  3372. e = new svg.Element.MISSING(node);
  3373. }
  3374. e.type = node.nodeName;
  3375. return e;
  3376. };
  3377. // load from url
  3378. svg.load = function (ctx, url) {
  3379. svg.loadXml(ctx, svg.ajax(url));
  3380. };
  3381. // load from xml
  3382. svg.loadXml = function (ctx, xml) {
  3383. svg.loadXmlDoc(ctx, svg.parseXml(xml));
  3384. };
  3385. svg.loadXmlDoc = function (ctx, dom) {
  3386. svg.init(ctx);
  3387. var mapXY = function (p) {
  3388. var e = ctx.canvas;
  3389. while (e) {
  3390. p.x -= e.offsetLeft;
  3391. p.y -= e.offsetTop;
  3392. e = e.offsetParent;
  3393. }
  3394. if (windowEnv.scrollX) p.x += windowEnv.scrollX;
  3395. if (windowEnv.scrollY) p.y += windowEnv.scrollY;
  3396. return p;
  3397. };
  3398. // bind mouse
  3399. if (svg.opts['ignoreMouse'] != true) {
  3400. ctx.canvas.onclick = function (e) {
  3401. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  3402. svg.Mouse.onclick(p.x, p.y);
  3403. };
  3404. ctx.canvas.onmousemove = function (e) {
  3405. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  3406. svg.Mouse.onmousemove(p.x, p.y);
  3407. };
  3408. }
  3409. var e = svg.CreateElement(dom.documentElement);
  3410. e.root = true;
  3411. e.addStylesFromStyleDefinition();
  3412. // render loop
  3413. var isFirstRender = true;
  3414. var draw = function () {
  3415. svg.ViewPort.Clear();
  3416. if (ctx.canvas.parentNode) {
  3417. svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight);
  3418. } else {
  3419. svg.ViewPort.SetCurrent(defaultClientWidth, defaultClientHeight);
  3420. }
  3421. if (svg.opts['ignoreDimensions'] != true && (isFirstRender || (svg.opts['scaleWidth'] == null && svg.opts['scaleHeight'] == null))) {
  3422. // set canvas size
  3423. if (e.style('width').hasValue()) {
  3424. ctx.canvas.width = e.style('width').toPixels('x');
  3425. if (ctx.canvas.style) { ctx.canvas.style.width = ctx.canvas.width + 'px'; }
  3426. }
  3427. if (e.style('height').hasValue()) {
  3428. ctx.canvas.height = e.style('height').toPixels('y');
  3429. if (ctx.canvas.style) { ctx.canvas.style.height = ctx.canvas.height + 'px'; }
  3430. }
  3431. }
  3432. var cWidth = ctx.canvas.clientWidth || ctx.canvas.width;
  3433. var cHeight = ctx.canvas.clientHeight || ctx.canvas.height;
  3434. if (svg.opts['ignoreDimensions'] == true && e.style('width').hasValue() && e.style('height').hasValue()) {
  3435. cWidth = e.style('width').toPixels('x');
  3436. cHeight = e.style('height').toPixels('y');
  3437. }
  3438. svg.ViewPort.SetCurrent(cWidth, cHeight);
  3439. if (svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX'];
  3440. if (svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY'];
  3441. if (svg.opts['scaleWidth'] != null || svg.opts['scaleHeight'] != null) {
  3442. var xRatio = null,
  3443. yRatio = null,
  3444. viewBox = svg.ToNumberArray(e.attribute('viewBox').value);
  3445. if (svg.opts['scaleWidth'] != null) {
  3446. if (e.attribute('width').hasValue()) xRatio = e.attribute('width').toPixels('x') / svg.opts['scaleWidth'];
  3447. else if (!isNaN(viewBox[2])) xRatio = viewBox[2] / svg.opts['scaleWidth'];
  3448. }
  3449. if (svg.opts['scaleHeight'] != null) {
  3450. if (e.attribute('height').hasValue()) yRatio = e.attribute('height').toPixels('y') / svg.opts['scaleHeight'];
  3451. else if (!isNaN(viewBox[3])) yRatio = viewBox[3] / svg.opts['scaleHeight'];
  3452. }
  3453. if (xRatio == null) { xRatio = yRatio; }
  3454. if (yRatio == null) { yRatio = xRatio; }
  3455. e.attribute('width', true).value = svg.opts['scaleWidth'];
  3456. e.attribute('height', true).value = svg.opts['scaleHeight'];
  3457. e.style('transform', true, true).value += ' scale(' + (1.0 / xRatio) + ',' + (1.0 / yRatio) + ')';
  3458. }
  3459. // clear and render
  3460. if (svg.opts['ignoreClear'] != true) {
  3461. ctx.clearRect(0, 0, cWidth, cHeight);
  3462. }
  3463. e.render(ctx);
  3464. if (isFirstRender) {
  3465. isFirstRender = false;
  3466. if (typeof svg.opts['renderCallback'] == 'function') svg.opts['renderCallback'](dom);
  3467. }
  3468. };
  3469. var waitingForImages = true;
  3470. if (svg.ImagesLoaded()) {
  3471. waitingForImages = false;
  3472. draw();
  3473. }
  3474. {
  3475. //In node, in the most cases, we don't need the animation listener.
  3476. svg.intervalID = setInterval(function () {
  3477. var needUpdate = false;
  3478. if (waitingForImages && svg.ImagesLoaded()) {
  3479. waitingForImages = false;
  3480. needUpdate = true;
  3481. }
  3482. // need update from mouse events?
  3483. if (svg.opts['ignoreMouse'] != true) {
  3484. needUpdate = needUpdate || svg.Mouse.hasEvents();
  3485. }
  3486. // need update from animations?
  3487. if (svg.opts['ignoreAnimation'] != true) {
  3488. for (var i = 0; i < svg.Animations.length; i++) {
  3489. var needAnimationUpdate = svg.Animations[i].update(1000 / svg.FRAMERATE);
  3490. needUpdate = needUpdate || needAnimationUpdate;
  3491. }
  3492. }
  3493. // need update from redraw?
  3494. if (typeof svg.opts['forceRedraw'] == 'function') {
  3495. if (svg.opts['forceRedraw']() == true) needUpdate = true;
  3496. }
  3497. // render if needed
  3498. if (needUpdate) {
  3499. draw();
  3500. svg.Mouse.runEvents(); // run and clear our events
  3501. }
  3502. }, 1000 / svg.FRAMERATE);
  3503. }
  3504. };
  3505. svg.stop = function () {
  3506. if (svg.intervalID) {
  3507. clearInterval(svg.intervalID);
  3508. }
  3509. };
  3510. svg.Mouse = new (function () {
  3511. this.events = [];
  3512. this.hasEvents = function () { return this.events.length != 0; };
  3513. this.onclick = function (x, y) {
  3514. this.events.push({
  3515. type: 'onclick',
  3516. x: x,
  3517. y: y,
  3518. run: function (e) { if (e.onclick) e.onclick(); }
  3519. });
  3520. };
  3521. this.onmousemove = function (x, y) {
  3522. this.events.push({
  3523. type: 'onmousemove',
  3524. x: x,
  3525. y: y,
  3526. run: function (e) { if (e.onmousemove) e.onmousemove(); }
  3527. });
  3528. };
  3529. this.eventElements = [];
  3530. this.checkPath = function (element, ctx) {
  3531. for (var i = 0; i < this.events.length; i++) {
  3532. var e = this.events[i];
  3533. if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;
  3534. }
  3535. };
  3536. this.checkBoundingBox = function (element, bb) {
  3537. if (!bb) {
  3538. return;
  3539. }
  3540. for (var i = 0; i < this.events.length; i++) {
  3541. var e = this.events[i];
  3542. if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;
  3543. }
  3544. };
  3545. this.runEvents = function () {
  3546. svg.ctx.canvas.style.cursor = '';
  3547. for (var i = 0; i < this.events.length; i++) {
  3548. var e = this.events[i];
  3549. var element = this.eventElements[i];
  3550. while (element) {
  3551. e.run(element);
  3552. element = element.parent;
  3553. }
  3554. }
  3555. // done running, clear
  3556. this.events = [];
  3557. this.eventElements = [];
  3558. };
  3559. });
  3560. return svg;
  3561. }
  3562. if (typeof CanvasRenderingContext2D != 'undefined') {
  3563. CanvasRenderingContext2D.prototype.drawSvg = function (s, dx, dy, dw, dh, opts) {
  3564. var cOpts = {
  3565. ignoreMouse: true,
  3566. ignoreAnimation: true,
  3567. ignoreDimensions: true,
  3568. ignoreClear: true,
  3569. offsetX: dx,
  3570. offsetY: dy,
  3571. scaleWidth: dw,
  3572. scaleHeight: dh
  3573. };
  3574. for (var prop in opts) {
  3575. if (opts.hasOwnProperty(prop)) {
  3576. cOpts[prop] = opts[prop];
  3577. }
  3578. }
  3579. canvg(this.canvas, s, cOpts);
  3580. };
  3581. }
  3582. // for tests
  3583. canvg._build = build;
  3584. module.exports = canvg;
  3585. });
  3586. return canvg_1;
  3587. })));