canvg.js 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101
  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].replace(')','');
  634. var transformType = this.Type[type];
  635. if (typeof transformType != 'undefined') {
  636. var transform = new transformType(s);
  637. transform.type = type;
  638. this.transforms.push(transform);
  639. }
  640. }
  641. }
  642. // aspect ratio
  643. svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {
  644. // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
  645. aspectRatio = svg.compressSpaces(aspectRatio);
  646. aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer
  647. var align = aspectRatio.split(' ')[0] || 'xMidYMid';
  648. var meetOrSlice = aspectRatio.split(' ')[1] || 'meet';
  649. // calculate scale
  650. var scaleX = width / desiredWidth;
  651. var scaleY = height / desiredHeight;
  652. var scaleMin = Math.min(scaleX, scaleY);
  653. var scaleMax = Math.max(scaleX, scaleY);
  654. if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; }
  655. if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; }
  656. refX = new svg.Property('refX', refX);
  657. refY = new svg.Property('refY', refY);
  658. if (refX.hasValue() && refY.hasValue()) {
  659. ctx.translate(-scaleMin * refX.toPixels('x'), -scaleMin * refY.toPixels('y'));
  660. }
  661. else {
  662. // align
  663. if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);
  664. if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);
  665. if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0);
  666. if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight);
  667. }
  668. // scale
  669. if (align == 'none') ctx.scale(scaleX, scaleY);
  670. else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin);
  671. else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax);
  672. // translate
  673. ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);
  674. }
  675. // elements
  676. svg.Element = {}
  677. svg.EmptyProperty = new svg.Property('EMPTY', '');
  678. svg.Element.ElementBase = function(node) {
  679. this.attributes = {};
  680. this.styles = {};
  681. this.stylesSpecificity = {};
  682. this.children = [];
  683. // get or create attribute
  684. this.attribute = function(name, createIfNotExists) {
  685. var a = this.attributes[name];
  686. if (a != null) return a;
  687. if (createIfNotExists == true) { a = new svg.Property(name, ''); this.attributes[name] = a; }
  688. return a || svg.EmptyProperty;
  689. }
  690. this.getHrefAttribute = function() {
  691. for (var a in this.attributes) {
  692. if (a == 'href' || a.match(/:href$/)) {
  693. return this.attributes[a];
  694. }
  695. }
  696. return svg.EmptyProperty;
  697. }
  698. // get or create style, crawls up node tree
  699. this.style = function(name, createIfNotExists, skipAncestors) {
  700. var s = this.styles[name];
  701. if (s != null) return s;
  702. var a = this.attribute(name);
  703. if (a != null && a.hasValue()) {
  704. this.styles[name] = a; // move up to me to cache
  705. return a;
  706. }
  707. if (skipAncestors != true) {
  708. var p = this.parent;
  709. if (p != null) {
  710. var ps = p.style(name);
  711. if (ps != null && ps.hasValue()) {
  712. return ps;
  713. }
  714. }
  715. }
  716. if (createIfNotExists == true) { s = new svg.Property(name, ''); this.styles[name] = s; }
  717. return s || svg.EmptyProperty;
  718. }
  719. // base render
  720. this.render = function(ctx) {
  721. // don't render display=none
  722. if (this.style('display').value == 'none') return;
  723. // don't render visibility=hidden
  724. if (this.style('visibility').value == 'hidden') return;
  725. ctx.save();
  726. if (this.style('mask').hasValue()) { // mask
  727. var mask = this.style('mask').getDefinition();
  728. if (mask != null) mask.apply(ctx, this);
  729. }
  730. else if (this.style('filter').hasValue()) { // filter
  731. var filter = this.style('filter').getDefinition();
  732. if (filter != null) filter.apply(ctx, this);
  733. }
  734. else {
  735. this.setContext(ctx);
  736. this.renderChildren(ctx);
  737. this.clearContext(ctx);
  738. }
  739. ctx.restore();
  740. }
  741. // base set context
  742. this.setContext = function(ctx) {
  743. // OVERRIDE ME!
  744. }
  745. // base clear context
  746. this.clearContext = function(ctx) {
  747. // OVERRIDE ME!
  748. }
  749. // base render children
  750. this.renderChildren = function(ctx) {
  751. for (var i=0; i<this.children.length; i++) {
  752. this.children[i].render(ctx);
  753. }
  754. }
  755. this.addChild = function(childNode, create) {
  756. var child = childNode;
  757. if (create) child = svg.CreateElement(childNode);
  758. child.parent = this;
  759. if (child.type != 'title') { this.children.push(child); }
  760. }
  761. this.addStylesFromStyleDefinition = function () {
  762. // add styles
  763. for (var selector in svg.Styles) {
  764. if (selector[0] != '@' && matchesSelector(node, selector)) {
  765. var styles = svg.Styles[selector];
  766. var specificity = svg.StylesSpecificity[selector];
  767. if (styles != null) {
  768. for (var name in styles) {
  769. var existingSpecificity = this.stylesSpecificity[name];
  770. if (typeof existingSpecificity == 'undefined') {
  771. existingSpecificity = '000';
  772. }
  773. if (specificity > existingSpecificity) {
  774. this.styles[name] = styles[name];
  775. this.stylesSpecificity[name] = specificity;
  776. }
  777. }
  778. }
  779. }
  780. }
  781. };
  782. // Microsoft Edge fix
  783. var allUppercase = new RegExp("^[A-Z\-]+$");
  784. var normalizeAttributeName = function (name) {
  785. if (allUppercase.test(name)) {
  786. return name.toLowerCase();
  787. }
  788. return name;
  789. };
  790. if (node != null && node.nodeType == 1) { //ELEMENT_NODE
  791. // add attributes
  792. for (var i=0; i<node.attributes.length; i++) {
  793. var attribute = node.attributes[i];
  794. var nodeName = normalizeAttributeName(attribute.nodeName);
  795. this.attributes[nodeName] = new svg.Property(nodeName, attribute.value);
  796. }
  797. this.addStylesFromStyleDefinition();
  798. // add inline styles
  799. if (this.attribute('style').hasValue()) {
  800. var styles = this.attribute('style').value.split(';');
  801. for (var i=0; i<styles.length; i++) {
  802. if (svg.trim(styles[i]) != '') {
  803. var style = styles[i].split(':');
  804. var name = svg.trim(style[0]);
  805. var value = svg.trim(style[1]);
  806. this.styles[name] = new svg.Property(name, value);
  807. }
  808. }
  809. }
  810. // add id
  811. if (this.attribute('id').hasValue()) {
  812. if (svg.Definitions[this.attribute('id').value] == null) {
  813. svg.Definitions[this.attribute('id').value] = this;
  814. }
  815. }
  816. // add children
  817. for (var i=0; i<node.childNodes.length; i++) {
  818. var childNode = node.childNodes[i];
  819. if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE
  820. if (this.captureTextNodes && (childNode.nodeType == 3 || childNode.nodeType == 4)) {
  821. var text = childNode.value || childNode.text || childNode.textContent || '';
  822. if (svg.compressSpaces(text) != '') {
  823. this.addChild(new svg.Element.tspan(childNode), false); // TEXT_NODE
  824. }
  825. }
  826. }
  827. }
  828. }
  829. svg.Element.RenderedElementBase = function(node) {
  830. this.base = svg.Element.ElementBase;
  831. this.base(node);
  832. this.setContext = function(ctx) {
  833. // fill
  834. if (this.style('fill').isUrlDefinition()) {
  835. var fs = this.style('fill').getFillStyleDefinition(this, this.style('fill-opacity'));
  836. if (fs != null) ctx.fillStyle = fs;
  837. }
  838. else if (this.style('fill').hasValue()) {
  839. var fillStyle = this.style('fill');
  840. if (fillStyle.value == 'currentColor') fillStyle.value = this.style('color').value;
  841. if (fillStyle.value != 'inherit') ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);
  842. }
  843. if (this.style('fill-opacity').hasValue()) {
  844. var fillStyle = new svg.Property('fill', ctx.fillStyle);
  845. fillStyle = fillStyle.addOpacity(this.style('fill-opacity'));
  846. ctx.fillStyle = fillStyle.value;
  847. }
  848. // stroke
  849. if (this.style('stroke').isUrlDefinition()) {
  850. var fs = this.style('stroke').getFillStyleDefinition(this, this.style('stroke-opacity'));
  851. if (fs != null) ctx.strokeStyle = fs;
  852. }
  853. else if (this.style('stroke').hasValue()) {
  854. var strokeStyle = this.style('stroke');
  855. if (strokeStyle.value == 'currentColor') strokeStyle.value = this.style('color').value;
  856. if (strokeStyle.value != 'inherit') ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);
  857. }
  858. if (this.style('stroke-opacity').hasValue()) {
  859. var strokeStyle = new svg.Property('stroke', ctx.strokeStyle);
  860. strokeStyle = strokeStyle.addOpacity(this.style('stroke-opacity'));
  861. ctx.strokeStyle = strokeStyle.value;
  862. }
  863. if (this.style('stroke-width').hasValue()) {
  864. var newLineWidth = this.style('stroke-width').toPixels();
  865. ctx.lineWidth = newLineWidth == 0 ? 0.001 : newLineWidth; // browsers don't respect 0
  866. }
  867. if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;
  868. if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;
  869. if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;
  870. if (this.style('stroke-dasharray').hasValue() && this.style('stroke-dasharray').value != 'none') {
  871. var gaps = svg.ToNumberArray(this.style('stroke-dasharray').value);
  872. if (typeof ctx.setLineDash != 'undefined') { ctx.setLineDash(gaps); }
  873. else if (typeof ctx.webkitLineDash != 'undefined') { ctx.webkitLineDash = gaps; }
  874. else if (typeof ctx.mozDash != 'undefined' && !(gaps.length==1 && gaps[0]==0)) { ctx.mozDash = gaps; }
  875. var offset = this.style('stroke-dashoffset').numValueOrDefault(1);
  876. if (typeof ctx.lineDashOffset != 'undefined') { ctx.lineDashOffset = offset; }
  877. else if (typeof ctx.webkitLineDashOffset != 'undefined') { ctx.webkitLineDashOffset = offset; }
  878. else if (typeof ctx.mozDashOffset != 'undefined') { ctx.mozDashOffset = offset; }
  879. }
  880. // font
  881. if (typeof ctx.font != 'undefined') {
  882. ctx.font = svg.Font.CreateFont(
  883. this.style('font-style').value,
  884. this.style('font-variant').value,
  885. this.style('font-weight').value,
  886. this.style('font-size').hasValue() ? this.style('font-size').toPixels() + 'px' : '',
  887. this.style('font-family').value).toString();
  888. }
  889. // transform
  890. if (this.style('transform', false, true).hasValue()) {
  891. var transform = new svg.Transform(this.style('transform', false, true).value);
  892. transform.apply(ctx);
  893. }
  894. // clip
  895. if (this.style('clip-path', false, true).hasValue()) {
  896. var clip = this.style('clip-path', false, true).getDefinition();
  897. if (clip != null) clip.apply(ctx);
  898. }
  899. // opacity
  900. if (this.style('opacity').hasValue()) {
  901. ctx.globalAlpha = this.style('opacity').numValue();
  902. }
  903. }
  904. }
  905. svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase;
  906. svg.Element.PathElementBase = function(node) {
  907. this.base = svg.Element.RenderedElementBase;
  908. this.base(node);
  909. this.path = function(ctx) {
  910. if (ctx != null) ctx.beginPath();
  911. return new svg.BoundingBox();
  912. }
  913. this.renderChildren = function(ctx) {
  914. this.path(ctx);
  915. svg.Mouse.checkPath(this, ctx);
  916. if (ctx.fillStyle != '') {
  917. if (this.style('fill-rule').valueOrDefault('inherit') != 'inherit') { ctx.fill(this.style('fill-rule').value); }
  918. else { ctx.fill(); }
  919. }
  920. if (ctx.strokeStyle != '') ctx.stroke();
  921. var markers = this.getMarkers();
  922. if (markers != null) {
  923. if (this.style('marker-start').isUrlDefinition()) {
  924. var marker = this.style('marker-start').getDefinition();
  925. marker.render(ctx, markers[0][0], markers[0][1]);
  926. }
  927. if (this.style('marker-mid').isUrlDefinition()) {
  928. var marker = this.style('marker-mid').getDefinition();
  929. for (var i=1;i<markers.length-1;i++) {
  930. marker.render(ctx, markers[i][0], markers[i][1]);
  931. }
  932. }
  933. if (this.style('marker-end').isUrlDefinition()) {
  934. var marker = this.style('marker-end').getDefinition();
  935. marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]);
  936. }
  937. }
  938. }
  939. this.getBoundingBox = function() {
  940. return this.path();
  941. }
  942. this.getMarkers = function() {
  943. return null;
  944. }
  945. }
  946. svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase;
  947. // svg element
  948. svg.Element.svg = function(node) {
  949. this.base = svg.Element.RenderedElementBase;
  950. this.base(node);
  951. this.baseClearContext = this.clearContext;
  952. this.clearContext = function(ctx) {
  953. this.baseClearContext(ctx);
  954. svg.ViewPort.RemoveCurrent();
  955. }
  956. this.baseSetContext = this.setContext;
  957. this.setContext = function(ctx) {
  958. // initial values and defaults
  959. ctx.strokeStyle = 'rgba(0,0,0,0)';
  960. ctx.lineCap = 'butt';
  961. ctx.lineJoin = 'miter';
  962. ctx.miterLimit = 4;
  963. if (typeof ctx.font != 'undefined' && typeof window.getComputedStyle != 'undefined') {
  964. ctx.font = window.getComputedStyle(ctx.canvas).getPropertyValue('font');
  965. }
  966. this.baseSetContext(ctx);
  967. // create new view port
  968. if (!this.attribute('x').hasValue()) this.attribute('x', true).value = 0;
  969. if (!this.attribute('y').hasValue()) this.attribute('y', true).value = 0;
  970. ctx.translate(this.attribute('x').toPixels('x'), this.attribute('y').toPixels('y'));
  971. var width = svg.ViewPort.width();
  972. var height = svg.ViewPort.height();
  973. if (!this.attribute('width').hasValue()) this.attribute('width', true).value = '100%';
  974. if (!this.attribute('height').hasValue()) this.attribute('height', true).value = '100%';
  975. if (typeof this.root == 'undefined') {
  976. width = this.attribute('width').toPixels('x');
  977. height = this.attribute('height').toPixels('y');
  978. var x = 0;
  979. var y = 0;
  980. if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {
  981. x = -this.attribute('refX').toPixels('x');
  982. y = -this.attribute('refY').toPixels('y');
  983. }
  984. if (this.attribute('overflow').valueOrDefault('hidden') != 'visible') {
  985. ctx.beginPath();
  986. ctx.moveTo(x, y);
  987. ctx.lineTo(width, y);
  988. ctx.lineTo(width, height);
  989. ctx.lineTo(x, height);
  990. ctx.closePath();
  991. ctx.clip();
  992. }
  993. }
  994. svg.ViewPort.SetCurrent(width, height);
  995. // viewbox
  996. if (this.attribute('viewBox').hasValue()) {
  997. var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
  998. var minX = viewBox[0];
  999. var minY = viewBox[1];
  1000. width = viewBox[2];
  1001. height = viewBox[3];
  1002. svg.AspectRatio(ctx,
  1003. this.attribute('preserveAspectRatio').value,
  1004. svg.ViewPort.width(),
  1005. width,
  1006. svg.ViewPort.height(),
  1007. height,
  1008. minX,
  1009. minY,
  1010. this.attribute('refX').value,
  1011. this.attribute('refY').value);
  1012. svg.ViewPort.RemoveCurrent();
  1013. svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
  1014. }
  1015. }
  1016. }
  1017. svg.Element.svg.prototype = new svg.Element.RenderedElementBase;
  1018. // rect element
  1019. svg.Element.rect = function(node) {
  1020. this.base = svg.Element.PathElementBase;
  1021. this.base(node);
  1022. this.path = function(ctx) {
  1023. var x = this.attribute('x').toPixels('x');
  1024. var y = this.attribute('y').toPixels('y');
  1025. var width = this.attribute('width').toPixels('x');
  1026. var height = this.attribute('height').toPixels('y');
  1027. var rx = this.attribute('rx').toPixels('x');
  1028. var ry = this.attribute('ry').toPixels('y');
  1029. if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;
  1030. if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;
  1031. rx = Math.min(rx, width / 2.0);
  1032. ry = Math.min(ry, height / 2.0);
  1033. if (ctx != null) {
  1034. ctx.beginPath();
  1035. ctx.moveTo(x + rx, y);
  1036. ctx.lineTo(x + width - rx, y);
  1037. ctx.quadraticCurveTo(x + width, y, x + width, y + ry)
  1038. ctx.lineTo(x + width, y + height - ry);
  1039. ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height)
  1040. ctx.lineTo(x + rx, y + height);
  1041. ctx.quadraticCurveTo(x, y + height, x, y + height - ry)
  1042. ctx.lineTo(x, y + ry);
  1043. ctx.quadraticCurveTo(x, y, x + rx, y)
  1044. ctx.closePath();
  1045. }
  1046. return new svg.BoundingBox(x, y, x + width, y + height);
  1047. }
  1048. }
  1049. svg.Element.rect.prototype = new svg.Element.PathElementBase;
  1050. // circle element
  1051. svg.Element.circle = function(node) {
  1052. this.base = svg.Element.PathElementBase;
  1053. this.base(node);
  1054. this.path = function(ctx) {
  1055. var cx = this.attribute('cx').toPixels('x');
  1056. var cy = this.attribute('cy').toPixels('y');
  1057. var r = this.attribute('r').toPixels();
  1058. if (ctx != null) {
  1059. ctx.beginPath();
  1060. ctx.arc(cx, cy, r, 0, Math.PI * 2, true);
  1061. ctx.closePath();
  1062. }
  1063. return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);
  1064. }
  1065. }
  1066. svg.Element.circle.prototype = new svg.Element.PathElementBase;
  1067. // ellipse element
  1068. svg.Element.ellipse = function(node) {
  1069. this.base = svg.Element.PathElementBase;
  1070. this.base(node);
  1071. this.path = function(ctx) {
  1072. var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
  1073. var rx = this.attribute('rx').toPixels('x');
  1074. var ry = this.attribute('ry').toPixels('y');
  1075. var cx = this.attribute('cx').toPixels('x');
  1076. var cy = this.attribute('cy').toPixels('y');
  1077. if (ctx != null) {
  1078. ctx.beginPath();
  1079. ctx.moveTo(cx, cy - ry);
  1080. ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);
  1081. ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);
  1082. ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);
  1083. ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);
  1084. ctx.closePath();
  1085. }
  1086. return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);
  1087. }
  1088. }
  1089. svg.Element.ellipse.prototype = new svg.Element.PathElementBase;
  1090. // line element
  1091. svg.Element.line = function(node) {
  1092. this.base = svg.Element.PathElementBase;
  1093. this.base(node);
  1094. this.getPoints = function() {
  1095. return [
  1096. new svg.Point(this.attribute('x1').toPixels('x'), this.attribute('y1').toPixels('y')),
  1097. new svg.Point(this.attribute('x2').toPixels('x'), this.attribute('y2').toPixels('y'))];
  1098. }
  1099. this.path = function(ctx) {
  1100. var points = this.getPoints();
  1101. if (ctx != null) {
  1102. ctx.beginPath();
  1103. ctx.moveTo(points[0].x, points[0].y);
  1104. ctx.lineTo(points[1].x, points[1].y);
  1105. }
  1106. return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);
  1107. }
  1108. this.getMarkers = function() {
  1109. var points = this.getPoints();
  1110. var a = points[0].angleTo(points[1]);
  1111. return [[points[0], a], [points[1], a]];
  1112. }
  1113. }
  1114. svg.Element.line.prototype = new svg.Element.PathElementBase;
  1115. // polyline element
  1116. svg.Element.polyline = function(node) {
  1117. this.base = svg.Element.PathElementBase;
  1118. this.base(node);
  1119. this.points = svg.CreatePath(this.attribute('points').value);
  1120. this.path = function(ctx) {
  1121. var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);
  1122. if (ctx != null) {
  1123. ctx.beginPath();
  1124. ctx.moveTo(this.points[0].x, this.points[0].y);
  1125. }
  1126. for (var i=1; i<this.points.length; i++) {
  1127. bb.addPoint(this.points[i].x, this.points[i].y);
  1128. if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);
  1129. }
  1130. return bb;
  1131. }
  1132. this.getMarkers = function() {
  1133. var markers = [];
  1134. for (var i=0; i<this.points.length - 1; i++) {
  1135. markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]);
  1136. }
  1137. if (markers.length > 0) {
  1138. markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]);
  1139. }
  1140. return markers;
  1141. }
  1142. }
  1143. svg.Element.polyline.prototype = new svg.Element.PathElementBase;
  1144. // polygon element
  1145. svg.Element.polygon = function(node) {
  1146. this.base = svg.Element.polyline;
  1147. this.base(node);
  1148. this.basePath = this.path;
  1149. this.path = function(ctx) {
  1150. var bb = this.basePath(ctx);
  1151. if (ctx != null) {
  1152. ctx.lineTo(this.points[0].x, this.points[0].y);
  1153. ctx.closePath();
  1154. }
  1155. return bb;
  1156. }
  1157. }
  1158. svg.Element.polygon.prototype = new svg.Element.polyline;
  1159. // path element
  1160. svg.Element.path = function(node) {
  1161. this.base = svg.Element.PathElementBase;
  1162. this.base(node);
  1163. var d = this.attribute('d').value;
  1164. // TODO: convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF
  1165. d = d.replace(/,/gm,' '); // get rid of all commas
  1166. // As the end of a match can also be the start of the next match, we need to run this replace twice.
  1167. for(var i=0; i<2; i++)
  1168. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // suffix commands with spaces
  1169. d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // prefix commands with spaces
  1170. d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits on +- signs
  1171. // Again, we need to run this twice to find all occurances
  1172. for(var i=0; i<2; i++)
  1173. d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when they start with a comma
  1174. d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax
  1175. d = svg.compressSpaces(d); // compress multiple spaces
  1176. d = svg.trim(d);
  1177. this.PathParser = new (function(d) {
  1178. this.tokens = d.split(' ');
  1179. this.reset = function() {
  1180. this.i = -1;
  1181. this.command = '';
  1182. this.previousCommand = '';
  1183. this.start = new svg.Point(0, 0);
  1184. this.control = new svg.Point(0, 0);
  1185. this.current = new svg.Point(0, 0);
  1186. this.points = [];
  1187. this.angles = [];
  1188. }
  1189. this.isEnd = function() {
  1190. return this.i >= this.tokens.length - 1;
  1191. }
  1192. this.isCommandOrEnd = function() {
  1193. if (this.isEnd()) return true;
  1194. return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null;
  1195. }
  1196. this.isRelativeCommand = function() {
  1197. switch(this.command)
  1198. {
  1199. case 'm':
  1200. case 'l':
  1201. case 'h':
  1202. case 'v':
  1203. case 'c':
  1204. case 's':
  1205. case 'q':
  1206. case 't':
  1207. case 'a':
  1208. case 'z':
  1209. return true;
  1210. break;
  1211. }
  1212. return false;
  1213. }
  1214. this.getToken = function() {
  1215. this.i++;
  1216. return this.tokens[this.i];
  1217. }
  1218. this.getScalar = function() {
  1219. return parseFloat(this.getToken());
  1220. }
  1221. this.nextCommand = function() {
  1222. this.previousCommand = this.command;
  1223. this.command = this.getToken();
  1224. }
  1225. this.getPoint = function() {
  1226. var p = new svg.Point(this.getScalar(), this.getScalar());
  1227. return this.makeAbsolute(p);
  1228. }
  1229. this.getAsControlPoint = function() {
  1230. var p = this.getPoint();
  1231. this.control = p;
  1232. return p;
  1233. }
  1234. this.getAsCurrentPoint = function() {
  1235. var p = this.getPoint();
  1236. this.current = p;
  1237. return p;
  1238. }
  1239. this.getReflectedControlPoint = function() {
  1240. if (this.previousCommand.toLowerCase() != 'c' &&
  1241. this.previousCommand.toLowerCase() != 's' &&
  1242. this.previousCommand.toLowerCase() != 'q' &&
  1243. this.previousCommand.toLowerCase() != 't' ){
  1244. return this.current;
  1245. }
  1246. // reflect point
  1247. var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);
  1248. return p;
  1249. }
  1250. this.makeAbsolute = function(p) {
  1251. if (this.isRelativeCommand()) {
  1252. p.x += this.current.x;
  1253. p.y += this.current.y;
  1254. }
  1255. return p;
  1256. }
  1257. this.addMarker = function(p, from, priorTo) {
  1258. // if the last angle isn't filled in because we didn't have this point yet ...
  1259. if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length-1] == null) {
  1260. this.angles[this.angles.length-1] = this.points[this.points.length-1].angleTo(priorTo);
  1261. }
  1262. this.addMarkerAngle(p, from == null ? null : from.angleTo(p));
  1263. }
  1264. this.addMarkerAngle = function(p, a) {
  1265. this.points.push(p);
  1266. this.angles.push(a);
  1267. }
  1268. this.getMarkerPoints = function() { return this.points; }
  1269. this.getMarkerAngles = function() {
  1270. for (var i=0; i<this.angles.length; i++) {
  1271. if (this.angles[i] == null) {
  1272. for (var j=i+1; j<this.angles.length; j++) {
  1273. if (this.angles[j] != null) {
  1274. this.angles[i] = this.angles[j];
  1275. break;
  1276. }
  1277. }
  1278. }
  1279. }
  1280. return this.angles;
  1281. }
  1282. })(d);
  1283. this.path = function(ctx) {
  1284. var pp = this.PathParser;
  1285. pp.reset();
  1286. var bb = new svg.BoundingBox();
  1287. if (ctx != null) ctx.beginPath();
  1288. while (!pp.isEnd()) {
  1289. pp.nextCommand();
  1290. switch (pp.command) {
  1291. case 'M':
  1292. case 'm':
  1293. var p = pp.getAsCurrentPoint();
  1294. pp.addMarker(p);
  1295. bb.addPoint(p.x, p.y);
  1296. if (ctx != null) ctx.moveTo(p.x, p.y);
  1297. pp.start = pp.current;
  1298. while (!pp.isCommandOrEnd()) {
  1299. var p = pp.getAsCurrentPoint();
  1300. pp.addMarker(p, pp.start);
  1301. bb.addPoint(p.x, p.y);
  1302. if (ctx != null) ctx.lineTo(p.x, p.y);
  1303. }
  1304. break;
  1305. case 'L':
  1306. case 'l':
  1307. while (!pp.isCommandOrEnd()) {
  1308. var c = pp.current;
  1309. var p = pp.getAsCurrentPoint();
  1310. pp.addMarker(p, c);
  1311. bb.addPoint(p.x, p.y);
  1312. if (ctx != null) ctx.lineTo(p.x, p.y);
  1313. }
  1314. break;
  1315. case 'H':
  1316. case 'h':
  1317. while (!pp.isCommandOrEnd()) {
  1318. var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);
  1319. pp.addMarker(newP, pp.current);
  1320. pp.current = newP;
  1321. bb.addPoint(pp.current.x, pp.current.y);
  1322. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1323. }
  1324. break;
  1325. case 'V':
  1326. case 'v':
  1327. while (!pp.isCommandOrEnd()) {
  1328. var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
  1329. pp.addMarker(newP, pp.current);
  1330. pp.current = newP;
  1331. bb.addPoint(pp.current.x, pp.current.y);
  1332. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1333. }
  1334. break;
  1335. case 'C':
  1336. case 'c':
  1337. while (!pp.isCommandOrEnd()) {
  1338. var curr = pp.current;
  1339. var p1 = pp.getPoint();
  1340. var cntrl = pp.getAsControlPoint();
  1341. var cp = pp.getAsCurrentPoint();
  1342. pp.addMarker(cp, cntrl, p1);
  1343. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1344. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1345. }
  1346. break;
  1347. case 'S':
  1348. case 's':
  1349. while (!pp.isCommandOrEnd()) {
  1350. var curr = pp.current;
  1351. var p1 = pp.getReflectedControlPoint();
  1352. var cntrl = pp.getAsControlPoint();
  1353. var cp = pp.getAsCurrentPoint();
  1354. pp.addMarker(cp, cntrl, p1);
  1355. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1356. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1357. }
  1358. break;
  1359. case 'Q':
  1360. case 'q':
  1361. while (!pp.isCommandOrEnd()) {
  1362. var curr = pp.current;
  1363. var cntrl = pp.getAsControlPoint();
  1364. var cp = pp.getAsCurrentPoint();
  1365. pp.addMarker(cp, cntrl, cntrl);
  1366. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1367. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1368. }
  1369. break;
  1370. case 'T':
  1371. case 't':
  1372. while (!pp.isCommandOrEnd()) {
  1373. var curr = pp.current;
  1374. var cntrl = pp.getReflectedControlPoint();
  1375. pp.control = cntrl;
  1376. var cp = pp.getAsCurrentPoint();
  1377. pp.addMarker(cp, cntrl, cntrl);
  1378. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1379. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1380. }
  1381. break;
  1382. case 'A':
  1383. case 'a':
  1384. while (!pp.isCommandOrEnd()) {
  1385. var curr = pp.current;
  1386. var rx = pp.getScalar();
  1387. var ry = pp.getScalar();
  1388. var xAxisRotation = pp.getScalar() * (Math.PI / 180.0);
  1389. var largeArcFlag = pp.getScalar();
  1390. var sweepFlag = pp.getScalar();
  1391. var cp = pp.getAsCurrentPoint();
  1392. // Conversion from endpoint to center parameterization
  1393. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  1394. // x1', y1'
  1395. var currp = new svg.Point(
  1396. Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,
  1397. -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
  1398. );
  1399. // adjust radii
  1400. var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2);
  1401. if (l > 1) {
  1402. rx *= Math.sqrt(l);
  1403. ry *= Math.sqrt(l);
  1404. }
  1405. // cx', cy'
  1406. var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
  1407. ((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))) /
  1408. (Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2))
  1409. );
  1410. if (isNaN(s)) s = 0;
  1411. var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
  1412. // cx, cy
  1413. var centp = new svg.Point(
  1414. (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
  1415. (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
  1416. );
  1417. // vector magnitude
  1418. var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); }
  1419. // ratio between two vectors
  1420. var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) }
  1421. // angle between two vectors
  1422. var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); }
  1423. // initial angle
  1424. var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]);
  1425. // angle delta
  1426. var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry];
  1427. var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry];
  1428. var ad = a(u, v);
  1429. if (r(u,v) <= -1) ad = Math.PI;
  1430. if (r(u,v) >= 1) ad = 0;
  1431. // for markers
  1432. var dir = 1 - sweepFlag ? 1.0 : -1.0;
  1433. var ah = a1 + dir * (ad / 2.0);
  1434. var halfWay = new svg.Point(
  1435. centp.x + rx * Math.cos(ah),
  1436. centp.y + ry * Math.sin(ah)
  1437. );
  1438. pp.addMarkerAngle(halfWay, ah - dir * Math.PI / 2);
  1439. pp.addMarkerAngle(cp, ah - dir * Math.PI);
  1440. bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better
  1441. if (ctx != null) {
  1442. var r = rx > ry ? rx : ry;
  1443. var sx = rx > ry ? 1 : rx / ry;
  1444. var sy = rx > ry ? ry / rx : 1;
  1445. ctx.translate(centp.x, centp.y);
  1446. ctx.rotate(xAxisRotation);
  1447. ctx.scale(sx, sy);
  1448. ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);
  1449. ctx.scale(1/sx, 1/sy);
  1450. ctx.rotate(-xAxisRotation);
  1451. ctx.translate(-centp.x, -centp.y);
  1452. }
  1453. }
  1454. break;
  1455. case 'Z':
  1456. case 'z':
  1457. if (ctx != null) ctx.closePath();
  1458. pp.current = pp.start;
  1459. }
  1460. }
  1461. return bb;
  1462. }
  1463. this.getMarkers = function() {
  1464. var points = this.PathParser.getMarkerPoints();
  1465. var angles = this.PathParser.getMarkerAngles();
  1466. var markers = [];
  1467. for (var i=0; i<points.length; i++) {
  1468. markers.push([points[i], angles[i]]);
  1469. }
  1470. return markers;
  1471. }
  1472. }
  1473. svg.Element.path.prototype = new svg.Element.PathElementBase;
  1474. // pattern element
  1475. svg.Element.pattern = function(node) {
  1476. this.base = svg.Element.ElementBase;
  1477. this.base(node);
  1478. this.createPattern = function(ctx, element) {
  1479. var width = this.attribute('width').toPixels('x', true);
  1480. var height = this.attribute('height').toPixels('y', true);
  1481. // render me using a temporary svg element
  1482. var tempSvg = new svg.Element.svg();
  1483. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1484. tempSvg.attributes['width'] = new svg.Property('width', width + 'px');
  1485. tempSvg.attributes['height'] = new svg.Property('height', height + 'px');
  1486. tempSvg.attributes['transform'] = new svg.Property('transform', this.attribute('patternTransform').value);
  1487. tempSvg.children = this.children;
  1488. var c = document.createElement('canvas');
  1489. c.width = width;
  1490. c.height = height;
  1491. var cctx = c.getContext('2d');
  1492. if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {
  1493. cctx.translate(this.attribute('x').toPixels('x', true), this.attribute('y').toPixels('y', true));
  1494. }
  1495. // render 3x3 grid so when we transform there's no white space on edges
  1496. for (var x=-1; x<=1; x++) {
  1497. for (var y=-1; y<=1; y++) {
  1498. cctx.save();
  1499. tempSvg.attributes['x'] = new svg.Property('x', x * c.width);
  1500. tempSvg.attributes['y'] = new svg.Property('y', y * c.height);
  1501. tempSvg.render(cctx);
  1502. cctx.restore();
  1503. }
  1504. }
  1505. var pattern = ctx.createPattern(c, 'repeat');
  1506. return pattern;
  1507. }
  1508. }
  1509. svg.Element.pattern.prototype = new svg.Element.ElementBase;
  1510. // marker element
  1511. svg.Element.marker = function(node) {
  1512. this.base = svg.Element.ElementBase;
  1513. this.base(node);
  1514. this.baseRender = this.render;
  1515. this.render = function(ctx, point, angle) {
  1516. ctx.translate(point.x, point.y);
  1517. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle);
  1518. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);
  1519. ctx.save();
  1520. // render me using a temporary svg element
  1521. var tempSvg = new svg.Element.svg();
  1522. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1523. tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);
  1524. tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);
  1525. tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);
  1526. tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);
  1527. tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));
  1528. tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));
  1529. tempSvg.children = this.children;
  1530. tempSvg.render(ctx);
  1531. ctx.restore();
  1532. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth);
  1533. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle);
  1534. ctx.translate(-point.x, -point.y);
  1535. }
  1536. }
  1537. svg.Element.marker.prototype = new svg.Element.ElementBase;
  1538. // definitions element
  1539. svg.Element.defs = function(node) {
  1540. this.base = svg.Element.ElementBase;
  1541. this.base(node);
  1542. this.render = function(ctx) {
  1543. // NOOP
  1544. }
  1545. }
  1546. svg.Element.defs.prototype = new svg.Element.ElementBase;
  1547. // base for gradients
  1548. svg.Element.GradientBase = function(node) {
  1549. this.base = svg.Element.ElementBase;
  1550. this.base(node);
  1551. this.stops = [];
  1552. for (var i=0; i<this.children.length; i++) {
  1553. var child = this.children[i];
  1554. if (child.type == 'stop') this.stops.push(child);
  1555. }
  1556. this.getGradient = function() {
  1557. // OVERRIDE ME!
  1558. }
  1559. this.gradientUnits = function () {
  1560. return this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');
  1561. }
  1562. this.attributesToInherit = ['gradientUnits'];
  1563. this.inheritStopContainer = function (stopsContainer) {
  1564. for (var i=0; i<this.attributesToInherit.length; i++) {
  1565. var attributeToInherit = this.attributesToInherit[i];
  1566. if (!this.attribute(attributeToInherit).hasValue() && stopsContainer.attribute(attributeToInherit).hasValue()) {
  1567. this.attribute(attributeToInherit, true).value = stopsContainer.attribute(attributeToInherit).value;
  1568. }
  1569. }
  1570. }
  1571. this.createGradient = function(ctx, element, parentOpacityProp) {
  1572. var stopsContainer = this;
  1573. if (this.getHrefAttribute().hasValue()) {
  1574. stopsContainer = this.getHrefAttribute().getDefinition();
  1575. this.inheritStopContainer(stopsContainer);
  1576. }
  1577. var addParentOpacity = function (color) {
  1578. if (parentOpacityProp.hasValue()) {
  1579. var p = new svg.Property('color', color);
  1580. return p.addOpacity(parentOpacityProp).value;
  1581. }
  1582. return color;
  1583. };
  1584. var g = this.getGradient(ctx, element);
  1585. if (g == null) return addParentOpacity(stopsContainer.stops[stopsContainer.stops.length - 1].color);
  1586. for (var i=0; i<stopsContainer.stops.length; i++) {
  1587. g.addColorStop(stopsContainer.stops[i].offset, addParentOpacity(stopsContainer.stops[i].color));
  1588. }
  1589. if (this.attribute('gradientTransform').hasValue()) {
  1590. // render as transformed pattern on temporary canvas
  1591. var rootView = svg.ViewPort.viewPorts[0];
  1592. var rect = new svg.Element.rect();
  1593. rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS/3.0);
  1594. rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS/3.0);
  1595. rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS);
  1596. rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS);
  1597. var group = new svg.Element.g();
  1598. group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value);
  1599. group.children = [ rect ];
  1600. var tempSvg = new svg.Element.svg();
  1601. tempSvg.attributes['x'] = new svg.Property('x', 0);
  1602. tempSvg.attributes['y'] = new svg.Property('y', 0);
  1603. tempSvg.attributes['width'] = new svg.Property('width', rootView.width);
  1604. tempSvg.attributes['height'] = new svg.Property('height', rootView.height);
  1605. tempSvg.children = [ group ];
  1606. var c = document.createElement('canvas');
  1607. c.width = rootView.width;
  1608. c.height = rootView.height;
  1609. var tempCtx = c.getContext('2d');
  1610. tempCtx.fillStyle = g;
  1611. tempSvg.render(tempCtx);
  1612. return tempCtx.createPattern(c, 'no-repeat');
  1613. }
  1614. return g;
  1615. }
  1616. }
  1617. svg.Element.GradientBase.prototype = new svg.Element.ElementBase;
  1618. // linear gradient element
  1619. svg.Element.linearGradient = function(node) {
  1620. this.base = svg.Element.GradientBase;
  1621. this.base(node);
  1622. this.attributesToInherit.push('x1');
  1623. this.attributesToInherit.push('y1');
  1624. this.attributesToInherit.push('x2');
  1625. this.attributesToInherit.push('y2');
  1626. this.getGradient = function(ctx, element) {
  1627. var bb = this.gradientUnits() == 'objectBoundingBox' ? element.getBoundingBox() : null;
  1628. if (!this.attribute('x1').hasValue()
  1629. && !this.attribute('y1').hasValue()
  1630. && !this.attribute('x2').hasValue()
  1631. && !this.attribute('y2').hasValue()) {
  1632. this.attribute('x1', true).value = 0;
  1633. this.attribute('y1', true).value = 0;
  1634. this.attribute('x2', true).value = 1;
  1635. this.attribute('y2', true).value = 0;
  1636. }
  1637. var x1 = (this.gradientUnits() == 'objectBoundingBox'
  1638. ? bb.x() + bb.width() * this.attribute('x1').numValue()
  1639. : this.attribute('x1').toPixels('x'));
  1640. var y1 = (this.gradientUnits() == 'objectBoundingBox'
  1641. ? bb.y() + bb.height() * this.attribute('y1').numValue()
  1642. : this.attribute('y1').toPixels('y'));
  1643. var x2 = (this.gradientUnits() == 'objectBoundingBox'
  1644. ? bb.x() + bb.width() * this.attribute('x2').numValue()
  1645. : this.attribute('x2').toPixels('x'));
  1646. var y2 = (this.gradientUnits() == 'objectBoundingBox'
  1647. ? bb.y() + bb.height() * this.attribute('y2').numValue()
  1648. : this.attribute('y2').toPixels('y'));
  1649. if (x1 == x2 && y1 == y2) return null;
  1650. return ctx.createLinearGradient(x1, y1, x2, y2);
  1651. }
  1652. }
  1653. svg.Element.linearGradient.prototype = new svg.Element.GradientBase;
  1654. // radial gradient element
  1655. svg.Element.radialGradient = function(node) {
  1656. this.base = svg.Element.GradientBase;
  1657. this.base(node);
  1658. this.attributesToInherit.push('cx');
  1659. this.attributesToInherit.push('cy');
  1660. this.attributesToInherit.push('r');
  1661. this.attributesToInherit.push('fx');
  1662. this.attributesToInherit.push('fy');
  1663. this.getGradient = function(ctx, element) {
  1664. var bb = element.getBoundingBox();
  1665. if (!this.attribute('cx').hasValue()) this.attribute('cx', true).value = '50%';
  1666. if (!this.attribute('cy').hasValue()) this.attribute('cy', true).value = '50%';
  1667. if (!this.attribute('r').hasValue()) this.attribute('r', true).value = '50%';
  1668. var cx = (this.gradientUnits() == 'objectBoundingBox'
  1669. ? bb.x() + bb.width() * this.attribute('cx').numValue()
  1670. : this.attribute('cx').toPixels('x'));
  1671. var cy = (this.gradientUnits() == 'objectBoundingBox'
  1672. ? bb.y() + bb.height() * this.attribute('cy').numValue()
  1673. : this.attribute('cy').toPixels('y'));
  1674. var fx = cx;
  1675. var fy = cy;
  1676. if (this.attribute('fx').hasValue()) {
  1677. fx = (this.gradientUnits() == 'objectBoundingBox'
  1678. ? bb.x() + bb.width() * this.attribute('fx').numValue()
  1679. : this.attribute('fx').toPixels('x'));
  1680. }
  1681. if (this.attribute('fy').hasValue()) {
  1682. fy = (this.gradientUnits() == 'objectBoundingBox'
  1683. ? bb.y() + bb.height() * this.attribute('fy').numValue()
  1684. : this.attribute('fy').toPixels('y'));
  1685. }
  1686. var r = (this.gradientUnits() == 'objectBoundingBox'
  1687. ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue()
  1688. : this.attribute('r').toPixels());
  1689. return ctx.createRadialGradient(fx, fy, 0, cx, cy, r);
  1690. }
  1691. }
  1692. svg.Element.radialGradient.prototype = new svg.Element.GradientBase;
  1693. // gradient stop element
  1694. svg.Element.stop = function(node) {
  1695. this.base = svg.Element.ElementBase;
  1696. this.base(node);
  1697. this.offset = this.attribute('offset').numValue();
  1698. if (this.offset < 0) this.offset = 0;
  1699. if (this.offset > 1) this.offset = 1;
  1700. var stopColor = this.style('stop-color', true);
  1701. if (stopColor.value === '') stopColor.value = '#000';
  1702. if (this.style('stop-opacity').hasValue()) stopColor = stopColor.addOpacity(this.style('stop-opacity'));
  1703. this.color = stopColor.value;
  1704. }
  1705. svg.Element.stop.prototype = new svg.Element.ElementBase;
  1706. // animation base element
  1707. svg.Element.AnimateBase = function(node) {
  1708. this.base = svg.Element.ElementBase;
  1709. this.base(node);
  1710. svg.Animations.push(this);
  1711. this.duration = 0.0;
  1712. this.begin = this.attribute('begin').toMilliseconds();
  1713. this.maxDuration = this.begin + this.attribute('dur').toMilliseconds();
  1714. this.getProperty = function() {
  1715. var attributeType = this.attribute('attributeType').value;
  1716. var attributeName = this.attribute('attributeName').value;
  1717. if (attributeType == 'CSS') {
  1718. return this.parent.style(attributeName, true);
  1719. }
  1720. return this.parent.attribute(attributeName, true);
  1721. };
  1722. this.initialValue = null;
  1723. this.initialUnits = '';
  1724. this.removed = false;
  1725. this.calcValue = function() {
  1726. // OVERRIDE ME!
  1727. return '';
  1728. }
  1729. this.update = function(delta) {
  1730. // set initial value
  1731. if (this.initialValue == null) {
  1732. this.initialValue = this.getProperty().value;
  1733. this.initialUnits = this.getProperty().getUnits();
  1734. }
  1735. // if we're past the end time
  1736. if (this.duration > this.maxDuration) {
  1737. // loop for indefinitely repeating animations
  1738. if (this.attribute('repeatCount').value == 'indefinite'
  1739. || this.attribute('repeatDur').value == 'indefinite') {
  1740. this.duration = 0.0
  1741. }
  1742. else if (this.attribute('fill').valueOrDefault('remove') == 'freeze' && !this.frozen) {
  1743. this.frozen = true;
  1744. this.parent.animationFrozen = true;
  1745. this.parent.animationFrozenValue = this.getProperty().value;
  1746. }
  1747. else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) {
  1748. this.removed = true;
  1749. this.getProperty().value = this.parent.animationFrozen ? this.parent.animationFrozenValue : this.initialValue;
  1750. return true;
  1751. }
  1752. return false;
  1753. }
  1754. this.duration = this.duration + delta;
  1755. // if we're past the begin time
  1756. var updated = false;
  1757. if (this.begin < this.duration) {
  1758. var newValue = this.calcValue(); // tween
  1759. if (this.attribute('type').hasValue()) {
  1760. // for transform, etc.
  1761. var type = this.attribute('type').value;
  1762. newValue = type + '(' + newValue + ')';
  1763. }
  1764. this.getProperty().value = newValue;
  1765. updated = true;
  1766. }
  1767. return updated;
  1768. }
  1769. this.from = this.attribute('from');
  1770. this.to = this.attribute('to');
  1771. this.values = this.attribute('values');
  1772. if (this.values.hasValue()) this.values.value = this.values.value.split(';');
  1773. // fraction of duration we've covered
  1774. this.progress = function() {
  1775. var ret = { progress: (this.duration - this.begin) / (this.maxDuration - this.begin) };
  1776. if (this.values.hasValue()) {
  1777. var p = ret.progress * (this.values.value.length - 1);
  1778. var lb = Math.floor(p), ub = Math.ceil(p);
  1779. ret.from = new svg.Property('from', parseFloat(this.values.value[lb]));
  1780. ret.to = new svg.Property('to', parseFloat(this.values.value[ub]));
  1781. ret.progress = (p - lb) / (ub - lb);
  1782. }
  1783. else {
  1784. ret.from = this.from;
  1785. ret.to = this.to;
  1786. }
  1787. return ret;
  1788. }
  1789. }
  1790. svg.Element.AnimateBase.prototype = new svg.Element.ElementBase;
  1791. // animate element
  1792. svg.Element.animate = function(node) {
  1793. this.base = svg.Element.AnimateBase;
  1794. this.base(node);
  1795. this.calcValue = function() {
  1796. var p = this.progress();
  1797. // tween value linearly
  1798. var newValue = p.from.numValue() + (p.to.numValue() - p.from.numValue()) * p.progress;
  1799. return newValue + this.initialUnits;
  1800. };
  1801. }
  1802. svg.Element.animate.prototype = new svg.Element.AnimateBase;
  1803. // animate color element
  1804. svg.Element.animateColor = function(node) {
  1805. this.base = svg.Element.AnimateBase;
  1806. this.base(node);
  1807. this.calcValue = function() {
  1808. var p = this.progress();
  1809. var from = new RGBColor(p.from.value);
  1810. var to = new RGBColor(p.to.value);
  1811. if (from.ok && to.ok) {
  1812. // tween color linearly
  1813. var r = from.r + (to.r - from.r) * p.progress;
  1814. var g = from.g + (to.g - from.g) * p.progress;
  1815. var b = from.b + (to.b - from.b) * p.progress;
  1816. return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')';
  1817. }
  1818. return this.attribute('from').value;
  1819. };
  1820. }
  1821. svg.Element.animateColor.prototype = new svg.Element.AnimateBase;
  1822. // animate transform element
  1823. svg.Element.animateTransform = function(node) {
  1824. this.base = svg.Element.AnimateBase;
  1825. this.base(node);
  1826. this.calcValue = function() {
  1827. var p = this.progress();
  1828. // tween value linearly
  1829. var from = svg.ToNumberArray(p.from.value);
  1830. var to = svg.ToNumberArray(p.to.value);
  1831. var newValue = '';
  1832. for (var i=0; i<from.length; i++) {
  1833. newValue += from[i] + (to[i] - from[i]) * p.progress + ' ';
  1834. }
  1835. return newValue;
  1836. };
  1837. }
  1838. svg.Element.animateTransform.prototype = new svg.Element.animate;
  1839. // font element
  1840. svg.Element.font = function(node) {
  1841. this.base = svg.Element.ElementBase;
  1842. this.base(node);
  1843. this.horizAdvX = this.attribute('horiz-adv-x').numValue();
  1844. this.isRTL = false;
  1845. this.isArabic = false;
  1846. this.fontFace = null;
  1847. this.missingGlyph = null;
  1848. this.glyphs = [];
  1849. for (var i=0; i<this.children.length; i++) {
  1850. var child = this.children[i];
  1851. if (child.type == 'font-face') {
  1852. this.fontFace = child;
  1853. if (child.style('font-family').hasValue()) {
  1854. svg.Definitions[child.style('font-family').value] = this;
  1855. }
  1856. }
  1857. else if (child.type == 'missing-glyph') this.missingGlyph = child;
  1858. else if (child.type == 'glyph') {
  1859. if (child.arabicForm != '') {
  1860. this.isRTL = true;
  1861. this.isArabic = true;
  1862. if (typeof this.glyphs[child.unicode] == 'undefined') this.glyphs[child.unicode] = [];
  1863. this.glyphs[child.unicode][child.arabicForm] = child;
  1864. }
  1865. else {
  1866. this.glyphs[child.unicode] = child;
  1867. }
  1868. }
  1869. }
  1870. }
  1871. svg.Element.font.prototype = new svg.Element.ElementBase;
  1872. // font-face element
  1873. svg.Element.fontface = function(node) {
  1874. this.base = svg.Element.ElementBase;
  1875. this.base(node);
  1876. this.ascent = this.attribute('ascent').value;
  1877. this.descent = this.attribute('descent').value;
  1878. this.unitsPerEm = this.attribute('units-per-em').numValue();
  1879. }
  1880. svg.Element.fontface.prototype = new svg.Element.ElementBase;
  1881. // missing-glyph element
  1882. svg.Element.missingglyph = function(node) {
  1883. this.base = svg.Element.path;
  1884. this.base(node);
  1885. this.horizAdvX = 0;
  1886. }
  1887. svg.Element.missingglyph.prototype = new svg.Element.path;
  1888. // glyph element
  1889. svg.Element.glyph = function(node) {
  1890. this.base = svg.Element.path;
  1891. this.base(node);
  1892. this.horizAdvX = this.attribute('horiz-adv-x').numValue();
  1893. this.unicode = this.attribute('unicode').value;
  1894. this.arabicForm = this.attribute('arabic-form').value;
  1895. }
  1896. svg.Element.glyph.prototype = new svg.Element.path;
  1897. // text element
  1898. svg.Element.text = function(node) {
  1899. this.captureTextNodes = true;
  1900. this.base = svg.Element.RenderedElementBase;
  1901. this.base(node);
  1902. this.baseSetContext = this.setContext;
  1903. this.setContext = function(ctx) {
  1904. this.baseSetContext(ctx);
  1905. var textBaseline = this.style('dominant-baseline').toTextBaseline();
  1906. if (textBaseline == null) textBaseline = this.style('alignment-baseline').toTextBaseline();
  1907. if (textBaseline != null) ctx.textBaseline = textBaseline;
  1908. }
  1909. this.getBoundingBox = function () {
  1910. var x = this.attribute('x').toPixels('x');
  1911. var y = this.attribute('y').toPixels('y');
  1912. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  1913. return new svg.BoundingBox(x, y - fontSize, x + Math.floor(fontSize * 2.0 / 3.0) * this.children[0].getText().length, y);
  1914. }
  1915. this.renderChildren = function(ctx) {
  1916. this.x = this.attribute('x').toPixels('x');
  1917. this.y = this.attribute('y').toPixels('y');
  1918. if (this.attribute('dx').hasValue()) this.x += this.attribute('dx').toPixels('x');
  1919. if (this.attribute('dy').hasValue()) this.y += this.attribute('dy').toPixels('y');
  1920. this.x += this.getAnchorDelta(ctx, this, 0);
  1921. for (var i=0; i<this.children.length; i++) {
  1922. this.renderChild(ctx, this, this, i);
  1923. }
  1924. }
  1925. this.getAnchorDelta = function (ctx, parent, startI) {
  1926. var textAnchor = this.style('text-anchor').valueOrDefault('start');
  1927. if (textAnchor != 'start') {
  1928. var width = 0;
  1929. for (var i=startI; i<parent.children.length; i++) {
  1930. var child = parent.children[i];
  1931. if (i > startI && child.attribute('x').hasValue()) break; // new group
  1932. width += child.measureTextRecursive(ctx);
  1933. }
  1934. return -1 * (textAnchor == 'end' ? width : width / 2.0);
  1935. }
  1936. return 0;
  1937. }
  1938. this.renderChild = function(ctx, textParent, parent, i) {
  1939. var child = parent.children[i];
  1940. if (child.attribute('x').hasValue()) {
  1941. child.x = child.attribute('x').toPixels('x') + textParent.getAnchorDelta(ctx, parent, i);
  1942. if (child.attribute('dx').hasValue()) child.x += child.attribute('dx').toPixels('x');
  1943. }
  1944. else {
  1945. if (child.attribute('dx').hasValue()) textParent.x += child.attribute('dx').toPixels('x');
  1946. child.x = textParent.x;
  1947. }
  1948. textParent.x = child.x + child.measureText(ctx);
  1949. if (child.attribute('y').hasValue()) {
  1950. child.y = child.attribute('y').toPixels('y');
  1951. if (child.attribute('dy').hasValue()) child.y += child.attribute('dy').toPixels('y');
  1952. }
  1953. else {
  1954. if (child.attribute('dy').hasValue()) textParent.y += child.attribute('dy').toPixels('y');
  1955. child.y = textParent.y;
  1956. }
  1957. textParent.y = child.y;
  1958. child.render(ctx);
  1959. for (var i=0; i<child.children.length; i++) {
  1960. textParent.renderChild(ctx, textParent, child, i);
  1961. }
  1962. }
  1963. }
  1964. svg.Element.text.prototype = new svg.Element.RenderedElementBase;
  1965. // text base
  1966. svg.Element.TextElementBase = function(node) {
  1967. this.base = svg.Element.RenderedElementBase;
  1968. this.base(node);
  1969. this.getGlyph = function(font, text, i) {
  1970. var c = text[i];
  1971. var glyph = null;
  1972. if (font.isArabic) {
  1973. var arabicForm = 'isolated';
  1974. if ((i==0 || text[i-1]==' ') && i<text.length-2 && text[i+1]!=' ') arabicForm = 'terminal';
  1975. if (i>0 && text[i-1]!=' ' && i<text.length-2 && text[i+1]!=' ') arabicForm = 'medial';
  1976. if (i>0 && text[i-1]!=' ' && (i == text.length-1 || text[i+1]==' ')) arabicForm = 'initial';
  1977. if (typeof font.glyphs[c] != 'undefined') {
  1978. glyph = font.glyphs[c][arabicForm];
  1979. if (glyph == null && font.glyphs[c].type == 'glyph') glyph = font.glyphs[c];
  1980. }
  1981. }
  1982. else {
  1983. glyph = font.glyphs[c];
  1984. }
  1985. if (glyph == null) glyph = font.missingGlyph;
  1986. return glyph;
  1987. }
  1988. this.renderChildren = function(ctx) {
  1989. var customFont = this.parent.style('font-family').getDefinition();
  1990. if (customFont != null) {
  1991. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  1992. var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle);
  1993. var text = this.getText();
  1994. if (customFont.isRTL) text = text.split("").reverse().join("");
  1995. var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
  1996. for (var i=0; i<text.length; i++) {
  1997. var glyph = this.getGlyph(customFont, text, i);
  1998. var scale = fontSize / customFont.fontFace.unitsPerEm;
  1999. ctx.translate(this.x, this.y);
  2000. ctx.scale(scale, -scale);
  2001. var lw = ctx.lineWidth;
  2002. ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize;
  2003. if (fontStyle == 'italic') ctx.transform(1, 0, .4, 1, 0, 0);
  2004. glyph.render(ctx);
  2005. if (fontStyle == 'italic') ctx.transform(1, 0, -.4, 1, 0, 0);
  2006. ctx.lineWidth = lw;
  2007. ctx.scale(1/scale, -1/scale);
  2008. ctx.translate(-this.x, -this.y);
  2009. this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm;
  2010. if (typeof dx[i] != 'undefined' && !isNaN(dx[i])) {
  2011. this.x += dx[i];
  2012. }
  2013. }
  2014. return;
  2015. }
  2016. if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
  2017. if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y);
  2018. }
  2019. this.getText = function() {
  2020. // OVERRIDE ME
  2021. }
  2022. this.measureTextRecursive = function(ctx) {
  2023. var width = this.measureText(ctx);
  2024. for (var i=0; i<this.children.length; i++) {
  2025. width += this.children[i].measureTextRecursive(ctx);
  2026. }
  2027. return width;
  2028. }
  2029. this.measureText = function(ctx) {
  2030. var customFont = this.parent.style('font-family').getDefinition();
  2031. if (customFont != null) {
  2032. var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
  2033. var measure = 0;
  2034. var text = this.getText();
  2035. if (customFont.isRTL) text = text.split("").reverse().join("");
  2036. var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
  2037. for (var i=0; i<text.length; i++) {
  2038. var glyph = this.getGlyph(customFont, text, i);
  2039. measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm;
  2040. if (typeof dx[i] != 'undefined' && !isNaN(dx[i])) {
  2041. measure += dx[i];
  2042. }
  2043. }
  2044. return measure;
  2045. }
  2046. var textToMeasure = svg.compressSpaces(this.getText());
  2047. if (!ctx.measureText) return textToMeasure.length * 10;
  2048. ctx.save();
  2049. this.setContext(ctx);
  2050. var width = ctx.measureText(textToMeasure).width;
  2051. ctx.restore();
  2052. return width;
  2053. }
  2054. }
  2055. svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase;
  2056. // tspan
  2057. svg.Element.tspan = function(node) {
  2058. this.captureTextNodes = true;
  2059. this.base = svg.Element.TextElementBase;
  2060. this.base(node);
  2061. this.text = svg.compressSpaces(node.value || node.text || node.textContent || '');
  2062. this.getText = function() {
  2063. // if this node has children, then they own the text
  2064. if (this.children.length > 0) { return ''; }
  2065. return this.text;
  2066. }
  2067. }
  2068. svg.Element.tspan.prototype = new svg.Element.TextElementBase;
  2069. // tref
  2070. svg.Element.tref = function(node) {
  2071. this.base = svg.Element.TextElementBase;
  2072. this.base(node);
  2073. this.getText = function() {
  2074. var element = this.getHrefAttribute().getDefinition();
  2075. if (element != null) return element.children[0].getText();
  2076. }
  2077. }
  2078. svg.Element.tref.prototype = new svg.Element.TextElementBase;
  2079. // a element
  2080. svg.Element.a = function(node) {
  2081. this.base = svg.Element.TextElementBase;
  2082. this.base(node);
  2083. this.hasText = node.childNodes.length > 0;
  2084. for (var i=0; i<node.childNodes.length; i++) {
  2085. if (node.childNodes[i].nodeType != 3) this.hasText = false;
  2086. }
  2087. // this might contain text
  2088. this.text = this.hasText ? node.childNodes[0].value : '';
  2089. this.getText = function() {
  2090. return this.text;
  2091. }
  2092. this.baseRenderChildren = this.renderChildren;
  2093. this.renderChildren = function(ctx) {
  2094. if (this.hasText) {
  2095. // render as text element
  2096. this.baseRenderChildren(ctx);
  2097. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  2098. svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.toPixels('y'), this.x + this.measureText(ctx), this.y));
  2099. }
  2100. else if (this.children.length > 0) {
  2101. // render as temporary group
  2102. var g = new svg.Element.g();
  2103. g.children = this.children;
  2104. g.parent = this;
  2105. g.render(ctx);
  2106. }
  2107. }
  2108. this.onclick = function() {
  2109. window.open(this.getHrefAttribute().value);
  2110. }
  2111. this.onmousemove = function() {
  2112. svg.ctx.canvas.style.cursor = 'pointer';
  2113. }
  2114. }
  2115. svg.Element.a.prototype = new svg.Element.TextElementBase;
  2116. // image element
  2117. svg.Element.image = function(node) {
  2118. this.base = svg.Element.RenderedElementBase;
  2119. this.base(node);
  2120. var href = this.getHrefAttribute().value;
  2121. if (href == '') { return; }
  2122. var isSvg = href.match(/\.svg$/)
  2123. svg.Images.push(this);
  2124. this.loaded = false;
  2125. if (!isSvg) {
  2126. this.img = document.createElement('img');
  2127. if (svg.opts['useCORS'] == true) { this.img.crossOrigin = 'Anonymous'; }
  2128. var self = this;
  2129. this.img.onload = function() { self.loaded = true; }
  2130. this.img.onerror = function() { svg.log('ERROR: image "' + href + '" not found'); self.loaded = true; }
  2131. this.img.src = href;
  2132. }
  2133. else {
  2134. this.img = svg.ajax(href);
  2135. this.loaded = true;
  2136. }
  2137. this.renderChildren = function(ctx) {
  2138. var x = this.attribute('x').toPixels('x');
  2139. var y = this.attribute('y').toPixels('y');
  2140. var width = this.attribute('width').toPixels('x');
  2141. var height = this.attribute('height').toPixels('y');
  2142. if (width == 0 || height == 0) return;
  2143. ctx.save();
  2144. if (isSvg) {
  2145. ctx.drawSvg(this.img, x, y, width, height);
  2146. }
  2147. else {
  2148. ctx.translate(x, y);
  2149. svg.AspectRatio(ctx,
  2150. this.attribute('preserveAspectRatio').value,
  2151. width,
  2152. this.img.width,
  2153. height,
  2154. this.img.height,
  2155. 0,
  2156. 0);
  2157. ctx.drawImage(this.img, 0, 0);
  2158. }
  2159. ctx.restore();
  2160. }
  2161. this.getBoundingBox = function() {
  2162. var x = this.attribute('x').toPixels('x');
  2163. var y = this.attribute('y').toPixels('y');
  2164. var width = this.attribute('width').toPixels('x');
  2165. var height = this.attribute('height').toPixels('y');
  2166. return new svg.BoundingBox(x, y, x + width, y + height);
  2167. }
  2168. }
  2169. svg.Element.image.prototype = new svg.Element.RenderedElementBase;
  2170. // group element
  2171. svg.Element.g = function(node) {
  2172. this.base = svg.Element.RenderedElementBase;
  2173. this.base(node);
  2174. this.getBoundingBox = function() {
  2175. var bb = new svg.BoundingBox();
  2176. for (var i=0; i<this.children.length; i++) {
  2177. bb.addBoundingBox(this.children[i].getBoundingBox());
  2178. }
  2179. return bb;
  2180. };
  2181. }
  2182. svg.Element.g.prototype = new svg.Element.RenderedElementBase;
  2183. // symbol element
  2184. svg.Element.symbol = function(node) {
  2185. this.base = svg.Element.RenderedElementBase;
  2186. this.base(node);
  2187. this.render = function(ctx) {
  2188. // NO RENDER
  2189. };
  2190. }
  2191. svg.Element.symbol.prototype = new svg.Element.RenderedElementBase;
  2192. // style element
  2193. svg.Element.style = function(node) {
  2194. this.base = svg.Element.ElementBase;
  2195. this.base(node);
  2196. // text, or spaces then CDATA
  2197. var css = ''
  2198. for (var i=0; i<node.childNodes.length; i++) {
  2199. css += node.childNodes[i].data;
  2200. }
  2201. css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(^[\s]*\/\/.*)/gm, ''); // remove comments
  2202. css = svg.compressSpaces(css); // replace whitespace
  2203. var cssDefs = css.split('}');
  2204. for (var i=0; i<cssDefs.length; i++) {
  2205. if (svg.trim(cssDefs[i]) != '') {
  2206. var cssDef = cssDefs[i].split('{');
  2207. var cssClasses = cssDef[0].split(',');
  2208. var cssProps = cssDef[1].split(';');
  2209. for (var j=0; j<cssClasses.length; j++) {
  2210. var cssClass = svg.trim(cssClasses[j]);
  2211. if (cssClass != '') {
  2212. var props = svg.Styles[cssClass] || {};
  2213. for (var k=0; k<cssProps.length; k++) {
  2214. var prop = cssProps[k].indexOf(':');
  2215. var name = cssProps[k].substr(0, prop);
  2216. var value = cssProps[k].substr(prop + 1, cssProps[k].length - prop);
  2217. if (name != null && value != null) {
  2218. props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value));
  2219. }
  2220. }
  2221. svg.Styles[cssClass] = props;
  2222. svg.StylesSpecificity[cssClass] = getSelectorSpecificity(cssClass);
  2223. if (cssClass == '@font-face') {
  2224. var fontFamily = props['font-family'].value.replace(/"/g,'');
  2225. var srcs = props['src'].value.split(',');
  2226. for (var s=0; s<srcs.length; s++) {
  2227. if (srcs[s].indexOf('format("svg")') > 0) {
  2228. var urlStart = srcs[s].indexOf('url');
  2229. var urlEnd = srcs[s].indexOf(')', urlStart);
  2230. var url = srcs[s].substr(urlStart + 5, urlEnd - urlStart - 6);
  2231. var doc = svg.parseXml(svg.ajax(url));
  2232. var fonts = doc.getElementsByTagName('font');
  2233. for (var f=0; f<fonts.length; f++) {
  2234. var font = svg.CreateElement(fonts[f]);
  2235. svg.Definitions[fontFamily] = font;
  2236. }
  2237. }
  2238. }
  2239. }
  2240. }
  2241. }
  2242. }
  2243. }
  2244. }
  2245. svg.Element.style.prototype = new svg.Element.ElementBase;
  2246. // use element
  2247. svg.Element.use = function(node) {
  2248. this.base = svg.Element.RenderedElementBase;
  2249. this.base(node);
  2250. this.baseSetContext = this.setContext;
  2251. this.setContext = function(ctx) {
  2252. this.baseSetContext(ctx);
  2253. if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').toPixels('x'), 0);
  2254. if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').toPixels('y'));
  2255. }
  2256. var element = this.getHrefAttribute().getDefinition();
  2257. this.path = function(ctx) {
  2258. if (element != null) element.path(ctx);
  2259. }
  2260. this.getBoundingBox = function() {
  2261. if (element != null) return element.getBoundingBox();
  2262. }
  2263. this.renderChildren = function(ctx) {
  2264. if (element != null) {
  2265. var tempSvg = element;
  2266. if (element.type == 'symbol') {
  2267. // render me using a temporary svg element in symbol cases (http://www.w3.org/TR/SVG/struct.html#UseElement)
  2268. tempSvg = new svg.Element.svg();
  2269. tempSvg.type = 'svg';
  2270. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', element.attribute('viewBox').value);
  2271. tempSvg.attributes['preserveAspectRatio'] = new svg.Property('preserveAspectRatio', element.attribute('preserveAspectRatio').value);
  2272. tempSvg.attributes['overflow'] = new svg.Property('overflow', element.attribute('overflow').value);
  2273. tempSvg.children = element.children;
  2274. }
  2275. if (tempSvg.type == 'svg') {
  2276. // if symbol or svg, inherit width/height from me
  2277. if (this.attribute('width').hasValue()) tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);
  2278. if (this.attribute('height').hasValue()) tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);
  2279. }
  2280. var oldParent = tempSvg.parent;
  2281. tempSvg.parent = null;
  2282. tempSvg.render(ctx);
  2283. tempSvg.parent = oldParent;
  2284. }
  2285. }
  2286. }
  2287. svg.Element.use.prototype = new svg.Element.RenderedElementBase;
  2288. // mask element
  2289. svg.Element.mask = function(node) {
  2290. this.base = svg.Element.ElementBase;
  2291. this.base(node);
  2292. this.apply = function(ctx, element) {
  2293. // render as temp svg
  2294. var x = this.attribute('x').toPixels('x');
  2295. var y = this.attribute('y').toPixels('y');
  2296. var width = this.attribute('width').toPixels('x');
  2297. var height = this.attribute('height').toPixels('y');
  2298. if (width == 0 && height == 0) {
  2299. var bb = new svg.BoundingBox();
  2300. for (var i=0; i<this.children.length; i++) {
  2301. bb.addBoundingBox(this.children[i].getBoundingBox());
  2302. }
  2303. var x = Math.floor(bb.x1);
  2304. var y = Math.floor(bb.y1);
  2305. var width = Math.floor(bb.width());
  2306. var height = Math.floor(bb.height());
  2307. }
  2308. // temporarily remove mask to avoid recursion
  2309. var mask = element.attribute('mask').value;
  2310. element.attribute('mask').value = '';
  2311. var cMask = document.createElement('canvas');
  2312. cMask.width = x + width;
  2313. cMask.height = y + height;
  2314. var maskCtx = cMask.getContext('2d');
  2315. this.renderChildren(maskCtx);
  2316. var c = document.createElement('canvas');
  2317. c.width = x + width;
  2318. c.height = y + height;
  2319. var tempCtx = c.getContext('2d');
  2320. element.render(tempCtx);
  2321. tempCtx.globalCompositeOperation = 'destination-in';
  2322. tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat');
  2323. tempCtx.fillRect(0, 0, x + width, y + height);
  2324. ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat');
  2325. ctx.fillRect(0, 0, x + width, y + height);
  2326. // reassign mask
  2327. element.attribute('mask').value = mask;
  2328. }
  2329. this.render = function(ctx) {
  2330. // NO RENDER
  2331. }
  2332. }
  2333. svg.Element.mask.prototype = new svg.Element.ElementBase;
  2334. // clip element
  2335. svg.Element.clipPath = function(node) {
  2336. this.base = svg.Element.ElementBase;
  2337. this.base(node);
  2338. this.apply = function(ctx) {
  2339. var oldBeginPath = CanvasRenderingContext2D.prototype.beginPath;
  2340. CanvasRenderingContext2D.prototype.beginPath = function () { };
  2341. var oldClosePath = CanvasRenderingContext2D.prototype.closePath;
  2342. CanvasRenderingContext2D.prototype.closePath = function () { };
  2343. oldBeginPath.call(ctx);
  2344. for (var i=0; i<this.children.length; i++) {
  2345. var child = this.children[i];
  2346. if (typeof child.path != 'undefined') {
  2347. var transform = null;
  2348. if (child.style('transform', false, true).hasValue()) {
  2349. transform = new svg.Transform(child.style('transform', false, true).value);
  2350. transform.apply(ctx);
  2351. }
  2352. child.path(ctx);
  2353. CanvasRenderingContext2D.prototype.closePath = oldClosePath;
  2354. if (transform) { transform.unapply(ctx); }
  2355. }
  2356. }
  2357. oldClosePath.call(ctx);
  2358. ctx.clip();
  2359. CanvasRenderingContext2D.prototype.beginPath = oldBeginPath;
  2360. CanvasRenderingContext2D.prototype.closePath = oldClosePath;
  2361. }
  2362. this.render = function(ctx) {
  2363. // NO RENDER
  2364. }
  2365. }
  2366. svg.Element.clipPath.prototype = new svg.Element.ElementBase;
  2367. // filters
  2368. svg.Element.filter = function(node) {
  2369. this.base = svg.Element.ElementBase;
  2370. this.base(node);
  2371. this.apply = function(ctx, element) {
  2372. // render as temp svg
  2373. var bb = element.getBoundingBox();
  2374. var x = Math.floor(bb.x1);
  2375. var y = Math.floor(bb.y1);
  2376. var width = Math.floor(bb.width());
  2377. var height = Math.floor(bb.height());
  2378. // temporarily remove filter to avoid recursion
  2379. var filter = element.style('filter').value;
  2380. element.style('filter').value = '';
  2381. var px = 0, py = 0;
  2382. for (var i=0; i<this.children.length; i++) {
  2383. var efd = this.children[i].extraFilterDistance || 0;
  2384. px = Math.max(px, efd);
  2385. py = Math.max(py, efd);
  2386. }
  2387. var c = document.createElement('canvas');
  2388. c.width = width + 2*px;
  2389. c.height = height + 2*py;
  2390. var tempCtx = c.getContext('2d');
  2391. tempCtx.translate(-x + px, -y + py);
  2392. element.render(tempCtx);
  2393. // apply filters
  2394. for (var i=0; i<this.children.length; i++) {
  2395. if (typeof this.children[i].apply == 'function') {
  2396. this.children[i].apply(tempCtx, 0, 0, width + 2*px, height + 2*py);
  2397. }
  2398. }
  2399. // render on me
  2400. ctx.drawImage(c, 0, 0, width + 2*px, height + 2*py, x - px, y - py, width + 2*px, height + 2*py);
  2401. // reassign filter
  2402. element.style('filter', true).value = filter;
  2403. }
  2404. this.render = function(ctx) {
  2405. // NO RENDER
  2406. }
  2407. }
  2408. svg.Element.filter.prototype = new svg.Element.ElementBase;
  2409. svg.Element.feMorphology = function(node) {
  2410. this.base = svg.Element.ElementBase;
  2411. this.base(node);
  2412. this.apply = function(ctx, x, y, width, height) {
  2413. // TODO: implement
  2414. }
  2415. }
  2416. svg.Element.feMorphology.prototype = new svg.Element.ElementBase;
  2417. svg.Element.feComposite = function(node) {
  2418. this.base = svg.Element.ElementBase;
  2419. this.base(node);
  2420. this.apply = function(ctx, x, y, width, height) {
  2421. // TODO: implement
  2422. }
  2423. }
  2424. svg.Element.feComposite.prototype = new svg.Element.ElementBase;
  2425. svg.Element.feColorMatrix = function(node) {
  2426. this.base = svg.Element.ElementBase;
  2427. this.base(node);
  2428. var matrix = svg.ToNumberArray(this.attribute('values').value);
  2429. switch (this.attribute('type').valueOrDefault('matrix')) { // http://www.w3.org/TR/SVG/filters.html#feColorMatrixElement
  2430. case 'saturate':
  2431. var s = matrix[0];
  2432. matrix = [0.213+0.787*s,0.715-0.715*s,0.072-0.072*s,0,0,
  2433. 0.213-0.213*s,0.715+0.285*s,0.072-0.072*s,0,0,
  2434. 0.213-0.213*s,0.715-0.715*s,0.072+0.928*s,0,0,
  2435. 0,0,0,1,0,
  2436. 0,0,0,0,1];
  2437. break;
  2438. case 'hueRotate':
  2439. var a = matrix[0] * Math.PI / 180.0;
  2440. var c = function (m1,m2,m3) { return m1 + Math.cos(a)*m2 + Math.sin(a)*m3; };
  2441. matrix = [c(0.213,0.787,-0.213),c(0.715,-0.715,-0.715),c(0.072,-0.072,0.928),0,0,
  2442. c(0.213,-0.213,0.143),c(0.715,0.285,0.140),c(0.072,-0.072,-0.283),0,0,
  2443. c(0.213,-0.213,-0.787),c(0.715,-0.715,0.715),c(0.072,0.928,0.072),0,0,
  2444. 0,0,0,1,0,
  2445. 0,0,0,0,1];
  2446. break;
  2447. case 'luminanceToAlpha':
  2448. matrix = [0,0,0,0,0,
  2449. 0,0,0,0,0,
  2450. 0,0,0,0,0,
  2451. 0.2125,0.7154,0.0721,0,0,
  2452. 0,0,0,0,1];
  2453. break;
  2454. }
  2455. function imGet(img, x, y, width, height, rgba) {
  2456. return img[y*width*4 + x*4 + rgba];
  2457. }
  2458. function imSet(img, x, y, width, height, rgba, val) {
  2459. img[y*width*4 + x*4 + rgba] = val;
  2460. }
  2461. function m(i, v) {
  2462. var mi = matrix[i];
  2463. return mi * (mi < 0 ? v - 255 : v);
  2464. }
  2465. this.apply = function(ctx, x, y, width, height) {
  2466. // assuming x==0 && y==0 for now
  2467. var srcData = ctx.getImageData(0, 0, width, height);
  2468. for (var y = 0; y < height; y++) {
  2469. for (var x = 0; x < width; x++) {
  2470. var r = imGet(srcData.data, x, y, width, height, 0);
  2471. var g = imGet(srcData.data, x, y, width, height, 1);
  2472. var b = imGet(srcData.data, x, y, width, height, 2);
  2473. var a = imGet(srcData.data, x, y, width, height, 3);
  2474. imSet(srcData.data, x, y, width, height, 0, m(0,r)+m(1,g)+m(2,b)+m(3,a)+m(4,1));
  2475. imSet(srcData.data, x, y, width, height, 1, m(5,r)+m(6,g)+m(7,b)+m(8,a)+m(9,1));
  2476. imSet(srcData.data, x, y, width, height, 2, m(10,r)+m(11,g)+m(12,b)+m(13,a)+m(14,1));
  2477. imSet(srcData.data, x, y, width, height, 3, m(15,r)+m(16,g)+m(17,b)+m(18,a)+m(19,1));
  2478. }
  2479. }
  2480. ctx.clearRect(0, 0, width, height);
  2481. ctx.putImageData(srcData, 0, 0);
  2482. }
  2483. }
  2484. svg.Element.feColorMatrix.prototype = new svg.Element.ElementBase;
  2485. svg.Element.feGaussianBlur = function(node) {
  2486. this.base = svg.Element.ElementBase;
  2487. this.base(node);
  2488. this.blurRadius = Math.floor(this.attribute('stdDeviation').numValue());
  2489. this.extraFilterDistance = this.blurRadius;
  2490. this.apply = function(ctx, x, y, width, height) {
  2491. if (typeof stackBlur.canvasRGBA == 'undefined') {
  2492. svg.log('ERROR: StackBlur.js must be included for blur to work');
  2493. return;
  2494. }
  2495. // StackBlur requires canvas be on document
  2496. ctx.canvas.id = svg.UniqueId();
  2497. ctx.canvas.style.display = 'none';
  2498. document.body.appendChild(ctx.canvas);
  2499. stackBlur.canvasRGBA(ctx.canvas.id, x, y, width, height, this.blurRadius);
  2500. document.body.removeChild(ctx.canvas);
  2501. }
  2502. }
  2503. svg.Element.feGaussianBlur.prototype = new svg.Element.ElementBase;
  2504. // title element, do nothing
  2505. svg.Element.title = function(node) {
  2506. }
  2507. svg.Element.title.prototype = new svg.Element.ElementBase;
  2508. // desc element, do nothing
  2509. svg.Element.desc = function(node) {
  2510. }
  2511. svg.Element.desc.prototype = new svg.Element.ElementBase;
  2512. svg.Element.MISSING = function(node) {
  2513. svg.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.');
  2514. }
  2515. svg.Element.MISSING.prototype = new svg.Element.ElementBase;
  2516. // element factory
  2517. svg.CreateElement = function(node) {
  2518. var className = node.nodeName.replace(/^[^:]+:/,''); // remove namespace
  2519. className = className.replace(/\-/g,''); // remove dashes
  2520. var e = null;
  2521. if (typeof svg.Element[className] != 'undefined') {
  2522. e = new svg.Element[className](node);
  2523. }
  2524. else {
  2525. e = new svg.Element.MISSING(node);
  2526. }
  2527. e.type = node.nodeName;
  2528. return e;
  2529. }
  2530. // load from url
  2531. svg.load = function(ctx, url) {
  2532. svg.loadXml(ctx, svg.ajax(url));
  2533. }
  2534. // load from xml
  2535. svg.loadXml = function(ctx, xml) {
  2536. svg.loadXmlDoc(ctx, svg.parseXml(xml));
  2537. }
  2538. svg.loadXmlDoc = function(ctx, dom) {
  2539. svg.init(ctx);
  2540. var mapXY = function(p) {
  2541. var e = ctx.canvas;
  2542. while (e) {
  2543. p.x -= e.offsetLeft;
  2544. p.y -= e.offsetTop;
  2545. e = e.offsetParent;
  2546. }
  2547. if (window.scrollX) p.x += window.scrollX;
  2548. if (window.scrollY) p.y += window.scrollY;
  2549. return p;
  2550. }
  2551. // bind mouse
  2552. if (svg.opts['ignoreMouse'] != true) {
  2553. ctx.canvas.onclick = function(e) {
  2554. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  2555. svg.Mouse.onclick(p.x, p.y);
  2556. };
  2557. ctx.canvas.onmousemove = function(e) {
  2558. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  2559. svg.Mouse.onmousemove(p.x, p.y);
  2560. };
  2561. }
  2562. var e = svg.CreateElement(dom.documentElement);
  2563. e.root = true;
  2564. e.addStylesFromStyleDefinition();
  2565. // render loop
  2566. var isFirstRender = true;
  2567. var draw = function() {
  2568. svg.ViewPort.Clear();
  2569. if (ctx.canvas.parentNode) svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight);
  2570. if (svg.opts['ignoreDimensions'] != true) {
  2571. // set canvas size
  2572. if (e.style('width').hasValue()) {
  2573. ctx.canvas.width = e.style('width').toPixels('x');
  2574. ctx.canvas.style.width = ctx.canvas.width + 'px';
  2575. }
  2576. if (e.style('height').hasValue()) {
  2577. ctx.canvas.height = e.style('height').toPixels('y');
  2578. ctx.canvas.style.height = ctx.canvas.height + 'px';
  2579. }
  2580. }
  2581. var cWidth = ctx.canvas.clientWidth || ctx.canvas.width;
  2582. var cHeight = ctx.canvas.clientHeight || ctx.canvas.height;
  2583. if (svg.opts['ignoreDimensions'] == true && e.style('width').hasValue() && e.style('height').hasValue()) {
  2584. cWidth = e.style('width').toPixels('x');
  2585. cHeight = e.style('height').toPixels('y');
  2586. }
  2587. svg.ViewPort.SetCurrent(cWidth, cHeight);
  2588. if (svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX'];
  2589. if (svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY'];
  2590. if (svg.opts['scaleWidth'] != null || svg.opts['scaleHeight'] != null) {
  2591. var xRatio = null, yRatio = null, viewBox = svg.ToNumberArray(e.attribute('viewBox').value);
  2592. if (svg.opts['scaleWidth'] != null) {
  2593. if (e.attribute('width').hasValue()) xRatio = e.attribute('width').toPixels('x') / svg.opts['scaleWidth'];
  2594. else if (!isNaN(viewBox[2])) xRatio = viewBox[2] / svg.opts['scaleWidth'];
  2595. }
  2596. if (svg.opts['scaleHeight'] != null) {
  2597. if (e.attribute('height').hasValue()) yRatio = e.attribute('height').toPixels('y') / svg.opts['scaleHeight'];
  2598. else if (!isNaN(viewBox[3])) yRatio = viewBox[3] / svg.opts['scaleHeight'];
  2599. }
  2600. if (xRatio == null) { xRatio = yRatio; }
  2601. if (yRatio == null) { yRatio = xRatio; }
  2602. e.attribute('width', true).value = svg.opts['scaleWidth'];
  2603. e.attribute('height', true).value = svg.opts['scaleHeight'];
  2604. e.style('transform', true, true).value += ' scale('+(1.0/xRatio)+','+(1.0/yRatio)+')';
  2605. }
  2606. // clear and render
  2607. if (svg.opts['ignoreClear'] != true) {
  2608. ctx.clearRect(0, 0, cWidth, cHeight);
  2609. }
  2610. e.render(ctx);
  2611. if (isFirstRender) {
  2612. isFirstRender = false;
  2613. if (typeof svg.opts['renderCallback'] == 'function') svg.opts['renderCallback'](dom);
  2614. }
  2615. }
  2616. var waitingForImages = true;
  2617. if (svg.ImagesLoaded()) {
  2618. waitingForImages = false;
  2619. draw();
  2620. }
  2621. svg.intervalID = setInterval(function() {
  2622. var needUpdate = false;
  2623. if (waitingForImages && svg.ImagesLoaded()) {
  2624. waitingForImages = false;
  2625. needUpdate = true;
  2626. }
  2627. // need update from mouse events?
  2628. if (svg.opts['ignoreMouse'] != true) {
  2629. needUpdate = needUpdate | svg.Mouse.hasEvents();
  2630. }
  2631. // need update from animations?
  2632. if (svg.opts['ignoreAnimation'] != true) {
  2633. for (var i=0; i<svg.Animations.length; i++) {
  2634. needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE);
  2635. }
  2636. }
  2637. // need update from redraw?
  2638. if (typeof svg.opts['forceRedraw'] == 'function') {
  2639. if (svg.opts['forceRedraw']() == true) needUpdate = true;
  2640. }
  2641. // render if needed
  2642. if (needUpdate) {
  2643. draw();
  2644. svg.Mouse.runEvents(); // run and clear our events
  2645. }
  2646. }, 1000 / svg.FRAMERATE);
  2647. }
  2648. svg.stop = function() {
  2649. if (svg.intervalID) {
  2650. clearInterval(svg.intervalID);
  2651. }
  2652. }
  2653. svg.Mouse = new (function() {
  2654. this.events = [];
  2655. this.hasEvents = function() { return this.events.length != 0; }
  2656. this.onclick = function(x, y) {
  2657. this.events.push({ type: 'onclick', x: x, y: y,
  2658. run: function(e) { if (e.onclick) e.onclick(); }
  2659. });
  2660. }
  2661. this.onmousemove = function(x, y) {
  2662. this.events.push({ type: 'onmousemove', x: x, y: y,
  2663. run: function(e) { if (e.onmousemove) e.onmousemove(); }
  2664. });
  2665. }
  2666. this.eventElements = [];
  2667. this.checkPath = function(element, ctx) {
  2668. for (var i=0; i<this.events.length; i++) {
  2669. var e = this.events[i];
  2670. if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;
  2671. }
  2672. }
  2673. this.checkBoundingBox = function(element, bb) {
  2674. for (var i=0; i<this.events.length; i++) {
  2675. var e = this.events[i];
  2676. if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;
  2677. }
  2678. }
  2679. this.runEvents = function() {
  2680. svg.ctx.canvas.style.cursor = '';
  2681. for (var i=0; i<this.events.length; i++) {
  2682. var e = this.events[i];
  2683. var element = this.eventElements[i];
  2684. while (element) {
  2685. e.run(element);
  2686. element = element.parent;
  2687. }
  2688. }
  2689. // done running, clear
  2690. this.events = [];
  2691. this.eventElements = [];
  2692. }
  2693. });
  2694. return svg;
  2695. };
  2696. if (typeof CanvasRenderingContext2D != 'undefined') {
  2697. CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh, opts) {
  2698. var cOpts = {
  2699. ignoreMouse: true,
  2700. ignoreAnimation: true,
  2701. ignoreDimensions: true,
  2702. ignoreClear: true,
  2703. offsetX: dx,
  2704. offsetY: dy,
  2705. scaleWidth: dw,
  2706. scaleHeight: dh
  2707. }
  2708. for(var prop in opts) {
  2709. if(opts.hasOwnProperty(prop)){
  2710. cOpts[prop] = opts[prop];
  2711. }
  2712. }
  2713. canvg(this.canvas, s, cOpts);
  2714. }
  2715. }
  2716. return canvg;
  2717. }));