Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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