canvg.js 100 KB

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