canvg.js 143 KB

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