canvg.js 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509
  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. if(!window.console) {
  10. window.console = {};
  11. window.console.log = function(str) {};
  12. window.console.dir = function(str) {};
  13. }
  14. // <3 IE
  15. if(!Array.indexOf){
  16. Array.prototype.indexOf = function(obj){
  17. for(var i=0; i<this.length; i++){
  18. if(this[i]==obj){
  19. return i;
  20. }
  21. }
  22. return -1;
  23. }
  24. }
  25. (function(){
  26. // canvg(target, s)
  27. // empty parameters: replace all 'svg' elements on page with 'canvas' elements
  28. // target: canvas element or the id of a canvas element
  29. // s: svg string or url to svg file
  30. // opts: optional hash of options
  31. // ignoreMouse: true => ignore mouse events
  32. // ignoreAnimation: true => ignore animations
  33. // ignoreDimensions: true => does not try to resize canvas
  34. // ignoreClear: true => does not clear canvas
  35. // offsetX: int => draws at a x offset
  36. // offsetY: int => draws at a y offset
  37. // scaleWidth: int => scales horizontally to width
  38. // scaleHeight: int => scales vertically to height
  39. // renderCallback: function => will call the function after the first render is completed
  40. // forceRedraw: function => will call the function on every frame, if it returns true, will redraw
  41. this.canvg = function (target, s, opts) {
  42. // no parameters
  43. if (target == null && s == null && opts == null) {
  44. var svgTags = document.getElementsByTagName('svg');
  45. for (var i=0; i<svgTags.length; i++) {
  46. var svgTag = svgTags[i];
  47. var c = document.createElement('canvas');
  48. c.width = svgTag.clientWidth;
  49. c.height = svgTag.clientHeight;
  50. svgTag.parentNode.insertBefore(c, svgTag);
  51. svgTag.parentNode.removeChild(svgTag);
  52. var div = document.createElement('div');
  53. div.appendChild(svgTag);
  54. canvg(c, div.innerHTML);
  55. }
  56. return;
  57. }
  58. if (typeof target == 'string') {
  59. target = document.getElementById(target);
  60. }
  61. // reuse class per canvas
  62. var svg;
  63. if (target.svg == null) {
  64. svg = build();
  65. target.svg = svg;
  66. }
  67. else {
  68. svg = target.svg;
  69. svg.stop();
  70. }
  71. svg.opts = opts;
  72. var ctx = target.getContext('2d');
  73. if (s.substr(0,1) == '<') {
  74. // load from xml string
  75. svg.loadXml(ctx, s);
  76. }
  77. else {
  78. // load from url
  79. svg.load(ctx, s);
  80. }
  81. }
  82. function build() {
  83. var svg = { };
  84. svg.FRAMERATE = 30;
  85. // globals
  86. svg.init = function(ctx) {
  87. svg.Definitions = {};
  88. svg.Styles = {};
  89. svg.Animations = [];
  90. svg.Images = [];
  91. svg.ctx = ctx;
  92. svg.ViewPort = new (function () {
  93. this.viewPorts = [];
  94. this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); }
  95. this.RemoveCurrent = function() { this.viewPorts.pop(); }
  96. this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; }
  97. this.width = function() { return this.Current().width; }
  98. this.height = function() { return this.Current().height; }
  99. this.ComputeSize = function(d) {
  100. if (d != null && typeof(d) == 'number') return d;
  101. if (d == 'x') return this.width();
  102. if (d == 'y') return this.height();
  103. return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2);
  104. }
  105. });
  106. }
  107. svg.init();
  108. // images loaded
  109. svg.ImagesLoaded = function() {
  110. for (var i=0; i<svg.Images.length; i++) {
  111. if (!svg.Images[i].loaded) return false;
  112. }
  113. return true;
  114. }
  115. // trim
  116. svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); }
  117. // compress spaces
  118. svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); }
  119. // ajax
  120. svg.ajax = function(url) {
  121. var AJAX;
  122. if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();}
  123. else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');}
  124. if(AJAX){
  125. AJAX.open('GET',url,false);
  126. AJAX.send(null);
  127. return AJAX.responseText;
  128. }
  129. return null;
  130. }
  131. // parse xml
  132. svg.parseXml = function(xml) {
  133. if (window.DOMParser)
  134. {
  135. var parser = new DOMParser();
  136. return parser.parseFromString(xml, 'text/xml');
  137. }
  138. else
  139. {
  140. xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
  141. var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
  142. xmlDoc.async = 'false';
  143. xmlDoc.loadXML(xml);
  144. return xmlDoc;
  145. }
  146. }
  147. svg.Property = function(name, value) {
  148. this.name = name;
  149. this.value = value;
  150. this.hasValue = function() {
  151. return (this.value != null && this.value != '');
  152. }
  153. // return the numerical value of the property
  154. this.numValue = function() {
  155. if (!this.hasValue()) return 0;
  156. var n = parseFloat(this.value);
  157. if ((this.value + '').match(/%$/)) {
  158. n = n / 100.0;
  159. }
  160. return n;
  161. }
  162. this.valueOrDefault = function(def) {
  163. if (this.hasValue()) return this.value;
  164. return def;
  165. }
  166. this.numValueOrDefault = function(def) {
  167. if (this.hasValue()) return this.numValue();
  168. return def;
  169. }
  170. /* EXTENSIONS */
  171. var that = this;
  172. // color extensions
  173. this.Color = {
  174. // augment the current color value with the opacity
  175. addOpacity: function(opacity) {
  176. var newValue = that.value;
  177. if (opacity != null && opacity != '') {
  178. var color = new RGBColor(that.value);
  179. if (color.ok) {
  180. newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')';
  181. }
  182. }
  183. return new svg.Property(that.name, newValue);
  184. }
  185. }
  186. // definition extensions
  187. this.Definition = {
  188. // get the definition from the definitions table
  189. getDefinition: function() {
  190. var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2');
  191. return svg.Definitions[name];
  192. },
  193. isUrl: function() {
  194. return that.value.indexOf('url(') == 0
  195. },
  196. getFillStyle: function(e) {
  197. var def = this.getDefinition();
  198. // gradient
  199. if (def != null && def.createGradient) {
  200. return def.createGradient(svg.ctx, e);
  201. }
  202. // pattern
  203. if (def != null && def.createPattern) {
  204. return def.createPattern(svg.ctx, e);
  205. }
  206. return null;
  207. }
  208. }
  209. // length extensions
  210. this.Length = {
  211. DPI: function(viewPort) {
  212. return 96.0; // TODO: compute?
  213. },
  214. EM: function(viewPort) {
  215. var em = 12;
  216. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  217. if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort);
  218. return em;
  219. },
  220. // get the length as pixels
  221. toPixels: function(viewPort) {
  222. if (!that.hasValue()) return 0;
  223. var s = that.value+'';
  224. if (s.match(/em$/)) return that.numValue() * this.EM(viewPort);
  225. if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0;
  226. if (s.match(/px$/)) return that.numValue();
  227. if (s.match(/pt$/)) return that.numValue() * 1.25;
  228. if (s.match(/pc$/)) return that.numValue() * 15;
  229. if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54;
  230. if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4;
  231. if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort);
  232. if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort);
  233. return that.numValue();
  234. }
  235. }
  236. // time extensions
  237. this.Time = {
  238. // get the time as milliseconds
  239. toMilliseconds: function() {
  240. if (!that.hasValue()) return 0;
  241. var s = that.value+'';
  242. if (s.match(/s$/)) return that.numValue() * 1000;
  243. if (s.match(/ms$/)) return that.numValue();
  244. return that.numValue();
  245. }
  246. }
  247. // angle extensions
  248. this.Angle = {
  249. // get the angle as radians
  250. toRadians: function() {
  251. if (!that.hasValue()) return 0;
  252. var s = that.value+'';
  253. if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0);
  254. if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0);
  255. if (s.match(/rad$/)) return that.numValue();
  256. return that.numValue() * (Math.PI / 180.0);
  257. }
  258. }
  259. }
  260. // fonts
  261. svg.Font = new (function() {
  262. this.Styles = ['normal','italic','oblique','inherit'];
  263. this.Variants = ['normal','small-caps','inherit'];
  264. this.Weights = ['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','inherit'];
  265. this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) {
  266. var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font);
  267. return {
  268. fontFamily: fontFamily || f.fontFamily,
  269. fontSize: fontSize || f.fontSize,
  270. fontStyle: fontStyle || f.fontStyle,
  271. fontWeight: fontWeight || f.fontWeight,
  272. fontVariant: fontVariant || f.fontVariant,
  273. toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') }
  274. }
  275. }
  276. var that = this;
  277. this.Parse = function(s) {
  278. var f = {};
  279. var d = svg.trim(svg.compressSpaces(s || '')).split(' ');
  280. var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false }
  281. var ff = '';
  282. for (var i=0; i<d.length; i++) {
  283. if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; }
  284. else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; }
  285. 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; }
  286. else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; }
  287. else { if (d[i] != 'inherit') ff += d[i]; }
  288. } if (ff != '') f.fontFamily = ff;
  289. return f;
  290. }
  291. });
  292. // points and paths
  293. svg.ToNumberArray = function(s) {
  294. var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' ');
  295. for (var i=0; i<a.length; i++) {
  296. a[i] = parseFloat(a[i]);
  297. }
  298. return a;
  299. }
  300. svg.Point = function(x, y) {
  301. this.x = x;
  302. this.y = y;
  303. this.angleTo = function(p) {
  304. return Math.atan2(p.y - this.y, p.x - this.x);
  305. }
  306. this.applyTransform = function(v) {
  307. var xp = this.x * v[0] + this.y * v[2] + v[4];
  308. var yp = this.x * v[1] + this.y * v[3] + v[5];
  309. this.x = xp;
  310. this.y = yp;
  311. }
  312. }
  313. svg.CreatePoint = function(s) {
  314. var a = svg.ToNumberArray(s);
  315. return new svg.Point(a[0], a[1]);
  316. }
  317. svg.CreatePath = function(s) {
  318. var a = svg.ToNumberArray(s);
  319. var path = [];
  320. for (var i=0; i<a.length; i+=2) {
  321. path.push(new svg.Point(a[i], a[i+1]));
  322. }
  323. return path;
  324. }
  325. // bounding box
  326. svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want
  327. this.x1 = Number.NaN;
  328. this.y1 = Number.NaN;
  329. this.x2 = Number.NaN;
  330. this.y2 = Number.NaN;
  331. this.x = function() { return this.x1; }
  332. this.y = function() { return this.y1; }
  333. this.width = function() { return this.x2 - this.x1; }
  334. this.height = function() { return this.y2 - this.y1; }
  335. this.addPoint = function(x, y) {
  336. if (x != null) {
  337. if (isNaN(this.x1) || isNaN(this.x2)) {
  338. this.x1 = x;
  339. this.x2 = x;
  340. }
  341. if (x < this.x1) this.x1 = x;
  342. if (x > this.x2) this.x2 = x;
  343. }
  344. if (y != null) {
  345. if (isNaN(this.y1) || isNaN(this.y2)) {
  346. this.y1 = y;
  347. this.y2 = y;
  348. }
  349. if (y < this.y1) this.y1 = y;
  350. if (y > this.y2) this.y2 = y;
  351. }
  352. }
  353. this.addX = function(x) { this.addPoint(x, null); }
  354. this.addY = function(y) { this.addPoint(null, y); }
  355. this.addBoundingBox = function(bb) {
  356. this.addPoint(bb.x1, bb.y1);
  357. this.addPoint(bb.x2, bb.y2);
  358. }
  359. this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) {
  360. var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0)
  361. var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0)
  362. var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0)
  363. var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0)
  364. this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y);
  365. }
  366. this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
  367. // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
  368. var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y];
  369. this.addPoint(p0[0], p0[1]);
  370. this.addPoint(p3[0], p3[1]);
  371. for (i=0; i<=1; i++) {
  372. var f = function(t) {
  373. return Math.pow(1-t, 3) * p0[i]
  374. + 3 * Math.pow(1-t, 2) * t * p1[i]
  375. + 3 * (1-t) * Math.pow(t, 2) * p2[i]
  376. + Math.pow(t, 3) * p3[i];
  377. }
  378. var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
  379. var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
  380. var c = 3 * p1[i] - 3 * p0[i];
  381. if (a == 0) {
  382. if (b == 0) continue;
  383. var t = -c / b;
  384. if (0 < t && t < 1) {
  385. if (i == 0) this.addX(f(t));
  386. if (i == 1) this.addY(f(t));
  387. }
  388. continue;
  389. }
  390. var b2ac = Math.pow(b, 2) - 4 * c * a;
  391. if (b2ac < 0) continue;
  392. var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
  393. if (0 < t1 && t1 < 1) {
  394. if (i == 0) this.addX(f(t1));
  395. if (i == 1) this.addY(f(t1));
  396. }
  397. var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
  398. if (0 < t2 && t2 < 1) {
  399. if (i == 0) this.addX(f(t2));
  400. if (i == 1) this.addY(f(t2));
  401. }
  402. }
  403. }
  404. this.isPointInBox = function(x, y) {
  405. return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2);
  406. }
  407. this.addPoint(x1, y1);
  408. this.addPoint(x2, y2);
  409. }
  410. // transforms
  411. svg.Transform = function(v) {
  412. var that = this;
  413. this.Type = {}
  414. // translate
  415. this.Type.translate = function(s) {
  416. this.p = svg.CreatePoint(s);
  417. this.apply = function(ctx) {
  418. ctx.translate(this.p.x || 0.0, this.p.y || 0.0);
  419. }
  420. this.applyToPoint = function(p) {
  421. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  422. }
  423. }
  424. // rotate
  425. this.Type.rotate = function(s) {
  426. var a = svg.ToNumberArray(s);
  427. this.angle = new svg.Property('angle', a[0]);
  428. this.cx = a[1] || 0;
  429. this.cy = a[2] || 0;
  430. this.apply = function(ctx) {
  431. ctx.translate(this.cx, this.cy);
  432. ctx.rotate(this.angle.Angle.toRadians());
  433. ctx.translate(-this.cx, -this.cy);
  434. }
  435. this.applyToPoint = function(p) {
  436. var a = this.angle.Angle.toRadians();
  437. p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
  438. p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]);
  439. p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]);
  440. }
  441. }
  442. this.Type.scale = function(s) {
  443. this.p = svg.CreatePoint(s);
  444. this.apply = function(ctx) {
  445. ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0);
  446. }
  447. this.applyToPoint = function(p) {
  448. p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]);
  449. }
  450. }
  451. this.Type.matrix = function(s) {
  452. this.m = svg.ToNumberArray(s);
  453. this.apply = function(ctx) {
  454. ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
  455. }
  456. this.applyToPoint = function(p) {
  457. p.applyTransform(this.m);
  458. }
  459. }
  460. this.Type.SkewBase = function(s) {
  461. this.base = that.Type.matrix;
  462. this.base(s);
  463. this.angle = new svg.Property('angle', s);
  464. }
  465. this.Type.SkewBase.prototype = new this.Type.matrix;
  466. this.Type.skewX = function(s) {
  467. this.base = that.Type.SkewBase;
  468. this.base(s);
  469. this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0];
  470. }
  471. this.Type.skewX.prototype = new this.Type.SkewBase;
  472. this.Type.skewY = function(s) {
  473. this.base = that.Type.SkewBase;
  474. this.base(s);
  475. this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0];
  476. }
  477. this.Type.skewY.prototype = new this.Type.SkewBase;
  478. this.transforms = [];
  479. this.apply = function(ctx) {
  480. for (var i=0; i<this.transforms.length; i++) {
  481. this.transforms[i].apply(ctx);
  482. }
  483. }
  484. this.applyToPoint = function(p) {
  485. for (var i=0; i<this.transforms.length; i++) {
  486. this.transforms[i].applyToPoint(p);
  487. }
  488. }
  489. var data = v.split(/\s(?=[a-z])/);
  490. for (var i=0; i<data.length; i++) {
  491. var type = data[i].split('(')[0];
  492. var s = data[i].split('(')[1].replace(')','');
  493. var transform = new this.Type[type](s);
  494. this.transforms.push(transform);
  495. }
  496. }
  497. // aspect ratio
  498. svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {
  499. // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
  500. aspectRatio = svg.compressSpaces(aspectRatio);
  501. aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer
  502. var align = aspectRatio.split(' ')[0] || 'xMidYMid';
  503. var meetOrSlice = aspectRatio.split(' ')[1] || 'meet';
  504. // calculate scale
  505. var scaleX = width / desiredWidth;
  506. var scaleY = height / desiredHeight;
  507. var scaleMin = Math.min(scaleX, scaleY);
  508. var scaleMax = Math.max(scaleX, scaleY);
  509. if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; }
  510. if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; }
  511. refX = new svg.Property('refX', refX);
  512. refY = new svg.Property('refY', refY);
  513. if (refX.hasValue() && refY.hasValue()) {
  514. ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y'));
  515. }
  516. else {
  517. // align
  518. if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);
  519. if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);
  520. if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0);
  521. if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight);
  522. }
  523. // scale
  524. if (align == 'none') ctx.scale(scaleX, scaleY);
  525. else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin);
  526. else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax);
  527. // translate
  528. ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);
  529. }
  530. // elements
  531. svg.Element = {}
  532. svg.Element.ElementBase = function(node) {
  533. this.attributes = {};
  534. this.styles = {};
  535. this.children = [];
  536. // get or create attribute
  537. this.attribute = function(name, createIfNotExists) {
  538. var a = this.attributes[name];
  539. if (a != null) return a;
  540. a = new svg.Property(name, '');
  541. if (createIfNotExists == true) this.attributes[name] = a;
  542. return a;
  543. }
  544. // get or create style
  545. this.style = function(name, createIfNotExists) {
  546. var s = this.styles[name];
  547. if (s != null) return s;
  548. var a = this.attribute(name);
  549. if (a != null && a.hasValue()) {
  550. return a;
  551. }
  552. s = new svg.Property(name, '');
  553. if (createIfNotExists == true) this.styles[name] = s;
  554. return s;
  555. }
  556. // base render
  557. this.render = function(ctx) {
  558. // don't render display=none
  559. if (this.attribute('display').value == 'none') return;
  560. ctx.save();
  561. this.setContext(ctx);
  562. this.renderChildren(ctx);
  563. this.clearContext(ctx);
  564. ctx.restore();
  565. }
  566. // base set context
  567. this.setContext = function(ctx) {
  568. // OVERRIDE ME!
  569. }
  570. // base clear context
  571. this.clearContext = function(ctx) {
  572. // OVERRIDE ME!
  573. }
  574. // base render children
  575. this.renderChildren = function(ctx) {
  576. for (var i=0; i<this.children.length; i++) {
  577. this.children[i].render(ctx);
  578. }
  579. }
  580. this.addChild = function(childNode, create) {
  581. var child = childNode;
  582. if (create) child = svg.CreateElement(childNode);
  583. child.parent = this;
  584. this.children.push(child);
  585. }
  586. if (node != null && node.nodeType == 1) { //ELEMENT_NODE
  587. // add children
  588. for (var i=0; i<node.childNodes.length; i++) {
  589. var childNode = node.childNodes[i];
  590. if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE
  591. }
  592. // add attributes
  593. for (var i=0; i<node.attributes.length; i++) {
  594. var attribute = node.attributes[i];
  595. this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue);
  596. }
  597. // add tag styles
  598. var styles = svg.Styles[this.type];
  599. if (styles != null) {
  600. for (var name in styles) {
  601. this.styles[name] = styles[name];
  602. }
  603. }
  604. // add class styles
  605. if (this.attribute('class').hasValue()) {
  606. var classes = svg.compressSpaces(this.attribute('class').value).split(' ');
  607. for (var j=0; j<classes.length; j++) {
  608. styles = svg.Styles['.'+classes[j]];
  609. if (styles != null) {
  610. for (var name in styles) {
  611. this.styles[name] = styles[name];
  612. }
  613. }
  614. }
  615. }
  616. // add inline styles
  617. if (this.attribute('style').hasValue()) {
  618. var styles = this.attribute('style').value.split(';');
  619. for (var i=0; i<styles.length; i++) {
  620. if (svg.trim(styles[i]) != '') {
  621. var style = styles[i].split(':');
  622. var name = svg.trim(style[0]);
  623. var value = svg.trim(style[1]);
  624. this.styles[name] = new svg.Property(name, value);
  625. }
  626. }
  627. }
  628. // add id
  629. if (this.attribute('id').hasValue()) {
  630. if (svg.Definitions[this.attribute('id').value] == null) {
  631. svg.Definitions[this.attribute('id').value] = this;
  632. }
  633. }
  634. }
  635. }
  636. svg.Element.RenderedElementBase = function(node) {
  637. this.base = svg.Element.ElementBase;
  638. this.base(node);
  639. this.setContext = function(ctx) {
  640. // fill
  641. if (this.style('fill').Definition.isUrl()) {
  642. var fs = this.style('fill').Definition.getFillStyle(this);
  643. if (fs != null) ctx.fillStyle = fs;
  644. }
  645. else if (this.style('fill').hasValue()) {
  646. var fillStyle = this.style('fill');
  647. if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value);
  648. ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);
  649. }
  650. // stroke
  651. if (this.style('stroke').Definition.isUrl()) {
  652. var fs = this.style('stroke').Definition.getFillStyle(this);
  653. if (fs != null) ctx.strokeStyle = fs;
  654. }
  655. else if (this.style('stroke').hasValue()) {
  656. var strokeStyle = this.style('stroke');
  657. if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value);
  658. ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);
  659. }
  660. if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels();
  661. if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;
  662. if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;
  663. if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;
  664. // font
  665. if (typeof(ctx.font) != 'undefined') {
  666. ctx.font = svg.Font.CreateFont(
  667. this.style('font-style').value,
  668. this.style('font-variant').value,
  669. this.style('font-weight').value,
  670. this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '',
  671. this.style('font-family').value).toString();
  672. }
  673. // transform
  674. if (this.attribute('transform').hasValue()) {
  675. var transform = new svg.Transform(this.attribute('transform').value);
  676. transform.apply(ctx);
  677. }
  678. // clip
  679. if (this.attribute('clip-path').hasValue()) {
  680. var clip = this.attribute('clip-path').Definition.getDefinition();
  681. if (clip != null) clip.apply(ctx);
  682. }
  683. // opacity
  684. if (this.style('opacity').hasValue()) {
  685. ctx.globalAlpha = this.style('opacity').numValue();
  686. }
  687. }
  688. }
  689. svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase;
  690. svg.Element.PathElementBase = function(node) {
  691. this.base = svg.Element.RenderedElementBase;
  692. this.base(node);
  693. this.path = function(ctx) {
  694. if (ctx != null) ctx.beginPath();
  695. return new svg.BoundingBox();
  696. }
  697. this.renderChildren = function(ctx) {
  698. this.path(ctx);
  699. svg.Mouse.checkPath(this, ctx);
  700. if (ctx.fillStyle != '') ctx.fill();
  701. if (ctx.strokeStyle != '') ctx.stroke();
  702. var markers = this.getMarkers();
  703. if (markers != null) {
  704. if (this.attribute('marker-start').Definition.isUrl()) {
  705. var marker = this.attribute('marker-start').Definition.getDefinition();
  706. marker.render(ctx, markers[0][0], markers[0][1]);
  707. }
  708. if (this.attribute('marker-mid').Definition.isUrl()) {
  709. var marker = this.attribute('marker-mid').Definition.getDefinition();
  710. for (var i=1;i<markers.length-1;i++) {
  711. marker.render(ctx, markers[i][0], markers[i][1]);
  712. }
  713. }
  714. if (this.attribute('marker-end').Definition.isUrl()) {
  715. var marker = this.attribute('marker-end').Definition.getDefinition();
  716. marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]);
  717. }
  718. }
  719. }
  720. this.getBoundingBox = function() {
  721. return this.path();
  722. }
  723. this.getMarkers = function() {
  724. return null;
  725. }
  726. }
  727. svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase;
  728. // svg element
  729. svg.Element.svg = function(node) {
  730. this.base = svg.Element.RenderedElementBase;
  731. this.base(node);
  732. this.baseClearContext = this.clearContext;
  733. this.clearContext = function(ctx) {
  734. this.baseClearContext(ctx);
  735. svg.ViewPort.RemoveCurrent();
  736. }
  737. this.baseSetContext = this.setContext;
  738. this.setContext = function(ctx) {
  739. // initial values
  740. ctx.strokeStyle = 'rgba(0,0,0,0)';
  741. ctx.lineCap = 'butt';
  742. ctx.lineJoin = 'miter';
  743. ctx.miterLimit = 4;
  744. this.baseSetContext(ctx);
  745. // create new view port
  746. if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {
  747. ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y'));
  748. }
  749. var width = svg.ViewPort.width();
  750. var height = svg.ViewPort.height();
  751. if (this.attribute('width').hasValue() && this.attribute('height').hasValue()) {
  752. width = this.attribute('width').Length.toPixels('x');
  753. height = this.attribute('height').Length.toPixels('y');
  754. var x = 0;
  755. var y = 0;
  756. if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {
  757. x = -this.attribute('refX').Length.toPixels('x');
  758. y = -this.attribute('refY').Length.toPixels('y');
  759. }
  760. ctx.beginPath();
  761. ctx.moveTo(x, y);
  762. ctx.lineTo(width, y);
  763. ctx.lineTo(width, height);
  764. ctx.lineTo(x, height);
  765. ctx.closePath();
  766. ctx.clip();
  767. }
  768. svg.ViewPort.SetCurrent(width, height);
  769. // viewbox
  770. if (this.attribute('viewBox').hasValue()) {
  771. var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
  772. var minX = viewBox[0];
  773. var minY = viewBox[1];
  774. width = viewBox[2];
  775. height = viewBox[3];
  776. svg.AspectRatio(ctx,
  777. this.attribute('preserveAspectRatio').value,
  778. svg.ViewPort.width(),
  779. width,
  780. svg.ViewPort.height(),
  781. height,
  782. minX,
  783. minY,
  784. this.attribute('refX').value,
  785. this.attribute('refY').value);
  786. svg.ViewPort.RemoveCurrent();
  787. svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
  788. }
  789. }
  790. }
  791. svg.Element.svg.prototype = new svg.Element.RenderedElementBase;
  792. // rect element
  793. svg.Element.rect = function(node) {
  794. this.base = svg.Element.PathElementBase;
  795. this.base(node);
  796. this.path = function(ctx) {
  797. var x = this.attribute('x').Length.toPixels('x');
  798. var y = this.attribute('y').Length.toPixels('y');
  799. var width = this.attribute('width').Length.toPixels('x');
  800. var height = this.attribute('height').Length.toPixels('y');
  801. var rx = this.attribute('rx').Length.toPixels('x');
  802. var ry = this.attribute('ry').Length.toPixels('y');
  803. if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;
  804. if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;
  805. if (ctx != null) {
  806. ctx.beginPath();
  807. ctx.moveTo(x + rx, y);
  808. ctx.lineTo(x + width - rx, y);
  809. ctx.quadraticCurveTo(x + width, y, x + width, y + ry)
  810. ctx.lineTo(x + width, y + height - ry);
  811. ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height)
  812. ctx.lineTo(x + rx, y + height);
  813. ctx.quadraticCurveTo(x, y + height, x, y + height - ry)
  814. ctx.lineTo(x, y + ry);
  815. ctx.quadraticCurveTo(x, y, x + rx, y)
  816. ctx.closePath();
  817. }
  818. return new svg.BoundingBox(x, y, x + width, y + height);
  819. }
  820. }
  821. svg.Element.rect.prototype = new svg.Element.PathElementBase;
  822. // circle element
  823. svg.Element.circle = function(node) {
  824. this.base = svg.Element.PathElementBase;
  825. this.base(node);
  826. this.path = function(ctx) {
  827. var cx = this.attribute('cx').Length.toPixels('x');
  828. var cy = this.attribute('cy').Length.toPixels('y');
  829. var r = this.attribute('r').Length.toPixels();
  830. if (ctx != null) {
  831. ctx.beginPath();
  832. ctx.arc(cx, cy, r, 0, Math.PI * 2, true);
  833. ctx.closePath();
  834. }
  835. return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);
  836. }
  837. }
  838. svg.Element.circle.prototype = new svg.Element.PathElementBase;
  839. // ellipse element
  840. svg.Element.ellipse = function(node) {
  841. this.base = svg.Element.PathElementBase;
  842. this.base(node);
  843. this.path = function(ctx) {
  844. var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
  845. var rx = this.attribute('rx').Length.toPixels('x');
  846. var ry = this.attribute('ry').Length.toPixels('y');
  847. var cx = this.attribute('cx').Length.toPixels('x');
  848. var cy = this.attribute('cy').Length.toPixels('y');
  849. if (ctx != null) {
  850. ctx.beginPath();
  851. ctx.moveTo(cx, cy - ry);
  852. ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);
  853. ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);
  854. ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);
  855. ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);
  856. ctx.closePath();
  857. }
  858. return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);
  859. }
  860. }
  861. svg.Element.ellipse.prototype = new svg.Element.PathElementBase;
  862. // line element
  863. svg.Element.line = function(node) {
  864. this.base = svg.Element.PathElementBase;
  865. this.base(node);
  866. this.getPoints = function() {
  867. return [
  868. new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')),
  869. new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))];
  870. }
  871. this.path = function(ctx) {
  872. var points = this.getPoints();
  873. if (ctx != null) {
  874. ctx.beginPath();
  875. ctx.moveTo(points[0].x, points[0].y);
  876. ctx.lineTo(points[1].x, points[1].y);
  877. }
  878. return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);
  879. }
  880. this.getMarkers = function() {
  881. var points = this.getPoints();
  882. var a = points[0].angleTo(points[1]);
  883. return [[points[0], a], [points[1], a]];
  884. }
  885. }
  886. svg.Element.line.prototype = new svg.Element.PathElementBase;
  887. // polyline element
  888. svg.Element.polyline = function(node) {
  889. this.base = svg.Element.PathElementBase;
  890. this.base(node);
  891. this.points = svg.CreatePath(this.attribute('points').value);
  892. this.path = function(ctx) {
  893. var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);
  894. if (ctx != null) {
  895. ctx.beginPath();
  896. ctx.moveTo(this.points[0].x, this.points[0].y);
  897. }
  898. for (var i=1; i<this.points.length; i++) {
  899. bb.addPoint(this.points[i].x, this.points[i].y);
  900. if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);
  901. }
  902. return bb;
  903. }
  904. this.getMarkers = function() {
  905. var markers = [];
  906. for (var i=0; i<this.points.length - 1; i++) {
  907. markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]);
  908. }
  909. markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]);
  910. return markers;
  911. }
  912. }
  913. svg.Element.polyline.prototype = new svg.Element.PathElementBase;
  914. // polygon element
  915. svg.Element.polygon = function(node) {
  916. this.base = svg.Element.polyline;
  917. this.base(node);
  918. this.basePath = this.path;
  919. this.path = function(ctx) {
  920. var bb = this.basePath(ctx);
  921. if (ctx != null) {
  922. ctx.lineTo(this.points[0].x, this.points[0].y);
  923. ctx.closePath();
  924. }
  925. return bb;
  926. }
  927. }
  928. svg.Element.polygon.prototype = new svg.Element.polyline;
  929. // path element
  930. svg.Element.path = function(node) {
  931. this.base = svg.Element.PathElementBase;
  932. this.base(node);
  933. var d = this.attribute('d').value;
  934. // TODO: floating points, convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF
  935. d = d.replace(/,/gm,' '); // get rid of all commas
  936. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
  937. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
  938. d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // separate commands from points
  939. d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from points
  940. d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma
  941. d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma
  942. d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax
  943. d = svg.compressSpaces(d); // compress multiple spaces
  944. d = svg.trim(d);
  945. this.PathParser = new (function(d) {
  946. this.tokens = d.split(' ');
  947. this.reset = function() {
  948. this.i = -1;
  949. this.command = '';
  950. this.previousCommand = '';
  951. this.start = new svg.Point(0, 0);
  952. this.control = new svg.Point(0, 0);
  953. this.current = new svg.Point(0, 0);
  954. this.points = [];
  955. this.angles = [];
  956. }
  957. this.isEnd = function() {
  958. return this.i >= this.tokens.length - 1;
  959. }
  960. this.isCommandOrEnd = function() {
  961. if (this.isEnd()) return true;
  962. return this.tokens[this.i + 1].match(/[A-Za-z]/) != null;
  963. }
  964. this.isRelativeCommand = function() {
  965. return this.command == this.command.toLowerCase();
  966. }
  967. this.getToken = function() {
  968. this.i = this.i + 1;
  969. return this.tokens[this.i];
  970. }
  971. this.getScalar = function() {
  972. return parseFloat(this.getToken());
  973. }
  974. this.nextCommand = function() {
  975. this.previousCommand = this.command;
  976. this.command = this.getToken();
  977. }
  978. this.getPoint = function() {
  979. var p = new svg.Point(this.getScalar(), this.getScalar());
  980. return this.makeAbsolute(p);
  981. }
  982. this.getAsControlPoint = function() {
  983. var p = this.getPoint();
  984. this.control = p;
  985. return p;
  986. }
  987. this.getAsCurrentPoint = function() {
  988. var p = this.getPoint();
  989. this.current = p;
  990. return p;
  991. }
  992. this.getReflectedControlPoint = function() {
  993. if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') {
  994. return this.current;
  995. }
  996. // reflect point
  997. var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);
  998. return p;
  999. }
  1000. this.makeAbsolute = function(p) {
  1001. if (this.isRelativeCommand()) {
  1002. p.x = this.current.x + p.x;
  1003. p.y = this.current.y + p.y;
  1004. }
  1005. return p;
  1006. }
  1007. this.addMarker = function(p, from) {
  1008. this.addMarkerAngle(p, from == null ? null : from.angleTo(p));
  1009. }
  1010. this.addMarkerAngle = function(p, a) {
  1011. this.points.push(p);
  1012. this.angles.push(a);
  1013. }
  1014. this.getMarkerPoints = function() { return this.points; }
  1015. this.getMarkerAngles = function() {
  1016. for (var i=0; i<this.angles.length; i++) {
  1017. if (this.angles[i] == null) {
  1018. for (var j=i+1; j<this.angles.length; j++) {
  1019. if (this.angles[j] != null) {
  1020. this.angles[i] = this.angles[j];
  1021. break;
  1022. }
  1023. }
  1024. }
  1025. }
  1026. return this.angles;
  1027. }
  1028. })(d);
  1029. this.path = function(ctx) {
  1030. var pp = this.PathParser;
  1031. pp.reset();
  1032. var bb = new svg.BoundingBox();
  1033. if(this.attribute('visibility').value=='hidden') return;
  1034. if (ctx != null) ctx.beginPath();
  1035. while (!pp.isEnd()) {
  1036. pp.nextCommand();
  1037. switch (pp.command.toUpperCase()) {
  1038. case 'M':
  1039. var p = pp.getAsCurrentPoint();
  1040. pp.addMarker(p);
  1041. bb.addPoint(p.x, p.y);
  1042. if (ctx != null) ctx.moveTo(p.x, p.y);
  1043. pp.start = pp.current;
  1044. while (!pp.isCommandOrEnd()) {
  1045. var p = pp.getAsCurrentPoint();
  1046. pp.addMarker(p);
  1047. bb.addPoint(p.x, p.y);
  1048. if (ctx != null) ctx.lineTo(p.x, p.y);
  1049. }
  1050. break;
  1051. case 'L':
  1052. while (!pp.isCommandOrEnd()) {
  1053. var c = pp.current;
  1054. var p = pp.getAsCurrentPoint();
  1055. pp.addMarker(p, c);
  1056. bb.addPoint(p.x, p.y);
  1057. if (ctx != null) ctx.lineTo(p.x, p.y);
  1058. }
  1059. break;
  1060. case 'H':
  1061. while (!pp.isCommandOrEnd()) {
  1062. var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);
  1063. pp.addMarker(newP, pp.current);
  1064. pp.current = newP;
  1065. bb.addPoint(pp.current.x, pp.current.y);
  1066. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1067. }
  1068. break;
  1069. case 'V':
  1070. while (!pp.isCommandOrEnd()) {
  1071. var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
  1072. pp.addMarker(newP, pp.current);
  1073. pp.current = newP;
  1074. bb.addPoint(pp.current.x, pp.current.y);
  1075. if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
  1076. }
  1077. break;
  1078. case 'C':
  1079. while (!pp.isCommandOrEnd()) {
  1080. var curr = pp.current;
  1081. var p1 = pp.getPoint();
  1082. var cntrl = pp.getAsControlPoint();
  1083. var cp = pp.getAsCurrentPoint();
  1084. pp.addMarker(cp, cntrl);
  1085. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1086. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1087. }
  1088. break;
  1089. case 'S':
  1090. while (!pp.isCommandOrEnd()) {
  1091. var curr = pp.current;
  1092. var p1 = pp.getReflectedControlPoint();
  1093. var cntrl = pp.getAsControlPoint();
  1094. var cp = pp.getAsCurrentPoint();
  1095. pp.addMarker(cp, cntrl);
  1096. bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1097. if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1098. }
  1099. break;
  1100. case 'Q':
  1101. while (!pp.isCommandOrEnd()) {
  1102. var curr = pp.current;
  1103. var cntrl = pp.getAsControlPoint();
  1104. var cp = pp.getAsCurrentPoint();
  1105. pp.addMarker(cp, cntrl);
  1106. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1107. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1108. }
  1109. break;
  1110. case 'T':
  1111. while (!pp.isCommandOrEnd()) {
  1112. var curr = pp.current;
  1113. var cntrl = pp.getReflectedControlPoint();
  1114. pp.control = cntrl;
  1115. var cp = pp.getAsCurrentPoint();
  1116. pp.addMarker(cp, cntrl);
  1117. bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
  1118. if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
  1119. }
  1120. break;
  1121. case 'A':
  1122. while (!pp.isCommandOrEnd()) {
  1123. var curr = pp.current;
  1124. var rx = pp.getScalar();
  1125. var ry = pp.getScalar();
  1126. var xAxisRotation = pp.getScalar() * (Math.PI / 180.0);
  1127. var largeArcFlag = pp.getScalar();
  1128. var sweepFlag = pp.getScalar();
  1129. var cp = pp.getAsCurrentPoint();
  1130. // Conversion from endpoint to center parameterization
  1131. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  1132. // x1', y1'
  1133. var currp = new svg.Point(
  1134. Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,
  1135. -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
  1136. );
  1137. // adjust radii
  1138. var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2);
  1139. if (l > 1) {
  1140. rx *= Math.sqrt(l);
  1141. ry *= Math.sqrt(l);
  1142. }
  1143. // cx', cy'
  1144. var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
  1145. ((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))) /
  1146. (Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2))
  1147. );
  1148. if (isNaN(s)) s = 0;
  1149. var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
  1150. // cx, cy
  1151. var centp = new svg.Point(
  1152. (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
  1153. (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
  1154. );
  1155. // vector magnitude
  1156. var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); }
  1157. // ratio between two vectors
  1158. var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) }
  1159. // angle between two vectors
  1160. var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); }
  1161. // initial angle
  1162. var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]);
  1163. // angle delta
  1164. var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry];
  1165. var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry];
  1166. var ad = a(u, v);
  1167. if (r(u,v) <= -1) ad = Math.PI;
  1168. if (r(u,v) >= 1) ad = 0;
  1169. if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI;
  1170. if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI;
  1171. // for markers
  1172. var halfWay = new svg.Point(
  1173. centp.x - rx * Math.cos((a1 + ad) / 2),
  1174. centp.y - ry * Math.sin((a1 + ad) / 2)
  1175. );
  1176. pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
  1177. pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
  1178. bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better
  1179. if (ctx != null) {
  1180. var r = rx > ry ? rx : ry;
  1181. var sx = rx > ry ? 1 : rx / ry;
  1182. var sy = rx > ry ? ry / rx : 1;
  1183. ctx.translate(centp.x, centp.y);
  1184. ctx.rotate(xAxisRotation);
  1185. ctx.scale(sx, sy);
  1186. ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);
  1187. ctx.scale(1/sx, 1/sy);
  1188. ctx.rotate(-xAxisRotation);
  1189. ctx.translate(-centp.x, -centp.y);
  1190. }
  1191. }
  1192. break;
  1193. case 'Z':
  1194. if (ctx != null) ctx.closePath();
  1195. pp.current = pp.start;
  1196. }
  1197. }
  1198. return bb;
  1199. }
  1200. this.getMarkers = function() {
  1201. var points = this.PathParser.getMarkerPoints();
  1202. var angles = this.PathParser.getMarkerAngles();
  1203. var markers = [];
  1204. for (var i=0; i<points.length; i++) {
  1205. markers.push([points[i], angles[i]]);
  1206. }
  1207. return markers;
  1208. }
  1209. }
  1210. svg.Element.path.prototype = new svg.Element.PathElementBase;
  1211. // pattern element
  1212. svg.Element.pattern = function(node) {
  1213. this.base = svg.Element.ElementBase;
  1214. this.base(node);
  1215. this.createPattern = function(ctx, element) {
  1216. // render me using a temporary svg element
  1217. var tempSvg = new svg.Element.svg();
  1218. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1219. tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value);
  1220. tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value);
  1221. tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);
  1222. tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);
  1223. tempSvg.children = this.children;
  1224. var c = document.createElement('canvas');
  1225. c.width = this.attribute('width').Length.toPixels();
  1226. c.height = this.attribute('height').Length.toPixels();
  1227. tempSvg.render(c.getContext('2d'));
  1228. return ctx.createPattern(c, 'repeat');
  1229. }
  1230. }
  1231. svg.Element.pattern.prototype = new svg.Element.ElementBase;
  1232. // marker element
  1233. svg.Element.marker = function(node) {
  1234. this.base = svg.Element.ElementBase;
  1235. this.base(node);
  1236. this.baseRender = this.render;
  1237. this.render = function(ctx, point, angle) {
  1238. ctx.translate(point.x, point.y);
  1239. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle);
  1240. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);
  1241. ctx.save();
  1242. // render me using a temporary svg element
  1243. var tempSvg = new svg.Element.svg();
  1244. tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
  1245. tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);
  1246. tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);
  1247. tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);
  1248. tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);
  1249. tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));
  1250. tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));
  1251. tempSvg.children = this.children;
  1252. tempSvg.render(ctx);
  1253. ctx.restore();
  1254. if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth);
  1255. if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle);
  1256. ctx.translate(-point.x, -point.y);
  1257. }
  1258. }
  1259. svg.Element.marker.prototype = new svg.Element.ElementBase;
  1260. // definitions element
  1261. svg.Element.defs = function(node) {
  1262. this.base = svg.Element.ElementBase;
  1263. this.base(node);
  1264. this.render = function(ctx) {
  1265. // NOOP
  1266. }
  1267. }
  1268. svg.Element.defs.prototype = new svg.Element.ElementBase;
  1269. // base for gradients
  1270. svg.Element.GradientBase = function(node) {
  1271. this.base = svg.Element.ElementBase;
  1272. this.base(node);
  1273. this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');
  1274. this.stops = [];
  1275. for (var i=0; i<this.children.length; i++) {
  1276. var child = this.children[i];
  1277. this.stops.push(child);
  1278. }
  1279. this.getGradient = function() {
  1280. // OVERRIDE ME!
  1281. }
  1282. this.createGradient = function(ctx, element) {
  1283. var stopsContainer = this;
  1284. if (this.attribute('xlink:href').hasValue()) {
  1285. stopsContainer = this.attribute('xlink:href').Definition.getDefinition();
  1286. }
  1287. var g = this.getGradient(ctx, element);
  1288. for (var i=0; i<stopsContainer.stops.length; i++) {
  1289. g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color);
  1290. }
  1291. return g;
  1292. }
  1293. }
  1294. svg.Element.GradientBase.prototype = new svg.Element.ElementBase;
  1295. // linear gradient element
  1296. svg.Element.linearGradient = function(node) {
  1297. this.base = svg.Element.GradientBase;
  1298. this.base(node);
  1299. this.getGradient = function(ctx, element) {
  1300. var bb = element.getBoundingBox();
  1301. var x1 = (this.gradientUnits == 'objectBoundingBox'
  1302. ? bb.x() + bb.width() * this.attribute('x1').numValue()
  1303. : this.attribute('x1').Length.toPixels('x'));
  1304. var y1 = (this.gradientUnits == 'objectBoundingBox'
  1305. ? bb.y() + bb.height() * this.attribute('y1').numValue()
  1306. : this.attribute('y1').Length.toPixels('y'));
  1307. var x2 = (this.gradientUnits == 'objectBoundingBox'
  1308. ? bb.x() + bb.width() * this.attribute('x2').numValue()
  1309. : this.attribute('x2').Length.toPixels('x'));
  1310. var y2 = (this.gradientUnits == 'objectBoundingBox'
  1311. ? bb.y() + bb.height() * this.attribute('y2').numValue()
  1312. : this.attribute('y2').Length.toPixels('y'));
  1313. var p1 = new svg.Point(x1, y1);
  1314. var p2 = new svg.Point(x2, y2);
  1315. if (this.attribute('gradientTransform').hasValue()) {
  1316. var transform = new svg.Transform(this.attribute('gradientTransform').value);
  1317. transform.applyToPoint(p1);
  1318. transform.applyToPoint(p2);
  1319. }
  1320. return ctx.createLinearGradient(p1.x, p1.y, p2.x, p2.y);
  1321. }
  1322. }
  1323. svg.Element.linearGradient.prototype = new svg.Element.GradientBase;
  1324. // radial gradient element
  1325. svg.Element.radialGradient = function(node) {
  1326. this.base = svg.Element.GradientBase;
  1327. this.base(node);
  1328. this.getGradient = function(ctx, element) {
  1329. var bb = element.getBoundingBox();
  1330. var cx = (this.gradientUnits == 'objectBoundingBox'
  1331. ? bb.x() + bb.width() * this.attribute('cx').numValue()
  1332. : this.attribute('cx').Length.toPixels('x'));
  1333. var cy = (this.gradientUnits == 'objectBoundingBox'
  1334. ? bb.y() + bb.height() * this.attribute('cy').numValue()
  1335. : this.attribute('cy').Length.toPixels('y'));
  1336. var fx = cx;
  1337. var fy = cy;
  1338. if (this.attribute('fx').hasValue()) {
  1339. fx = (this.gradientUnits == 'objectBoundingBox'
  1340. ? bb.x() + bb.width() * this.attribute('fx').numValue()
  1341. : this.attribute('fx').Length.toPixels('x'));
  1342. }
  1343. if (this.attribute('fy').hasValue()) {
  1344. fy = (this.gradientUnits == 'objectBoundingBox'
  1345. ? bb.y() + bb.height() * this.attribute('fy').numValue()
  1346. : this.attribute('fy').Length.toPixels('y'));
  1347. }
  1348. var r = (this.gradientUnits == 'objectBoundingBox'
  1349. ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue()
  1350. : this.attribute('r').Length.toPixels());
  1351. var c = new svg.Point(cx, cy);
  1352. var f = new svg.Point(fx, fy);
  1353. if (this.attribute('gradientTransform').hasValue()) {
  1354. var transform = new svg.Transform(this.attribute('gradientTransform').value);
  1355. transform.applyToPoint(c);
  1356. transform.applyToPoint(f);
  1357. for (var i=0; i<transform.transforms.length; i++) {
  1358. // average the scaling part of the transform, apply to radius
  1359. var scale1 = transform.transforms[i].m[0];
  1360. var scale2 = transform.transforms[i].m[3];
  1361. r = r * ((scale1 + scale2) / 2.0);
  1362. }
  1363. }
  1364. return ctx.createRadialGradient(f.x, f.y, 0, c.x, c.y, r);
  1365. }
  1366. }
  1367. svg.Element.radialGradient.prototype = new svg.Element.GradientBase;
  1368. // gradient stop element
  1369. svg.Element.stop = function(node) {
  1370. this.base = svg.Element.ElementBase;
  1371. this.base(node);
  1372. this.offset = this.attribute('offset').numValue();
  1373. var stopColor = this.style('stop-color');
  1374. if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value);
  1375. this.color = stopColor.value;
  1376. }
  1377. svg.Element.stop.prototype = new svg.Element.ElementBase;
  1378. // animation base element
  1379. svg.Element.AnimateBase = function(node) {
  1380. this.base = svg.Element.ElementBase;
  1381. this.base(node);
  1382. svg.Animations.push(this);
  1383. this.duration = 0.0;
  1384. this.begin = this.attribute('begin').Time.toMilliseconds();
  1385. this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds();
  1386. this.getProperty = function() {
  1387. var attributeType = this.attribute('attributeType').value;
  1388. var attributeName = this.attribute('attributeName').value;
  1389. if (attributeType == 'CSS') {
  1390. return this.parent.style(attributeName, true);
  1391. }
  1392. return this.parent.attribute(attributeName, true);
  1393. };
  1394. this.initialValue = null;
  1395. this.removed = false;
  1396. this.calcValue = function() {
  1397. // OVERRIDE ME!
  1398. return '';
  1399. }
  1400. this.update = function(delta) {
  1401. // set initial value
  1402. if (this.initialValue == null) {
  1403. this.initialValue = this.getProperty().value;
  1404. }
  1405. // if we're past the end time
  1406. if (this.duration > this.maxDuration) {
  1407. // loop for indefinitely repeating animations
  1408. if (this.attribute('repeatCount').value == 'indefinite') {
  1409. this.duration = 0.0
  1410. }
  1411. else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) {
  1412. this.removed = true;
  1413. this.getProperty().value = this.initialValue;
  1414. return true;
  1415. }
  1416. else {
  1417. return false; // no updates made
  1418. }
  1419. }
  1420. this.duration = this.duration + delta;
  1421. // if we're past the begin time
  1422. var updated = false;
  1423. if (this.begin < this.duration) {
  1424. var newValue = this.calcValue(); // tween
  1425. if (this.attribute('type').hasValue()) {
  1426. // for transform, etc.
  1427. var type = this.attribute('type').value;
  1428. newValue = type + '(' + newValue + ')';
  1429. }
  1430. this.getProperty().value = newValue;
  1431. updated = true;
  1432. }
  1433. return updated;
  1434. }
  1435. // fraction of duration we've covered
  1436. this.progress = function() {
  1437. return ((this.duration - this.begin) / (this.maxDuration - this.begin));
  1438. }
  1439. }
  1440. svg.Element.AnimateBase.prototype = new svg.Element.ElementBase;
  1441. // animate element
  1442. svg.Element.animate = function(node) {
  1443. this.base = svg.Element.AnimateBase;
  1444. this.base(node);
  1445. this.calcValue = function() {
  1446. var from = this.attribute('from').numValue();
  1447. var to = this.attribute('to').numValue();
  1448. // tween value linearly
  1449. return from + (to - from) * this.progress();
  1450. };
  1451. }
  1452. svg.Element.animate.prototype = new svg.Element.AnimateBase;
  1453. // animate color element
  1454. svg.Element.animateColor = function(node) {
  1455. this.base = svg.Element.AnimateBase;
  1456. this.base(node);
  1457. this.calcValue = function() {
  1458. var from = new RGBColor(this.attribute('from').value);
  1459. var to = new RGBColor(this.attribute('to').value);
  1460. if (from.ok && to.ok) {
  1461. // tween color linearly
  1462. var r = from.r + (to.r - from.r) * this.progress();
  1463. var g = from.g + (to.g - from.g) * this.progress();
  1464. var b = from.b + (to.b - from.b) * this.progress();
  1465. return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')';
  1466. }
  1467. return this.attribute('from').value;
  1468. };
  1469. }
  1470. svg.Element.animateColor.prototype = new svg.Element.AnimateBase;
  1471. // animate transform element
  1472. svg.Element.animateTransform = function(node) {
  1473. this.base = svg.Element.animate;
  1474. this.base(node);
  1475. }
  1476. svg.Element.animateTransform.prototype = new svg.Element.animate;
  1477. // text element
  1478. svg.Element.text = function(node) {
  1479. this.base = svg.Element.RenderedElementBase;
  1480. this.base(node);
  1481. if (node != null) {
  1482. // add children
  1483. this.children = [];
  1484. for (var i=0; i<node.childNodes.length; i++) {
  1485. var childNode = node.childNodes[i];
  1486. if (childNode.nodeType == 1) { // capture tspan and tref nodes
  1487. this.addChild(childNode, true);
  1488. }
  1489. else if (childNode.nodeType == 3) { // capture text
  1490. this.addChild(new svg.Element.tspan(childNode), false);
  1491. }
  1492. }
  1493. }
  1494. this.baseSetContext = this.setContext;
  1495. this.setContext = function(ctx) {
  1496. this.baseSetContext(ctx);
  1497. if (this.attribute('text-anchor').hasValue()) {
  1498. var textAnchor = this.attribute('text-anchor').value;
  1499. ctx.textAlign = textAnchor == 'middle' ? 'center' : textAnchor;
  1500. }
  1501. if (this.attribute('alignment-baseline').hasValue()) ctx.textBaseline = this.attribute('alignment-baseline').value;
  1502. }
  1503. this.renderChildren = function(ctx) {
  1504. if(this.attribute('visibility').value=='hidden') return;
  1505. var x = this.attribute('x').Length.toPixels('x');
  1506. var y = this.attribute('y').Length.toPixels('y');
  1507. for (var i=0; i<this.children.length; i++) {
  1508. var child = this.children[i];
  1509. if (child.attribute('x').hasValue()) {
  1510. child.x = child.attribute('x').Length.toPixels('x');
  1511. }
  1512. else {
  1513. if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x');
  1514. child.x = x;
  1515. x += child.measureText(ctx);
  1516. }
  1517. if (child.attribute('y').hasValue()) {
  1518. child.y = child.attribute('y').Length.toPixels('y');
  1519. }
  1520. else {
  1521. if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y');
  1522. child.y = y;
  1523. }
  1524. child.render(ctx);
  1525. }
  1526. }
  1527. }
  1528. svg.Element.text.prototype = new svg.Element.RenderedElementBase;
  1529. // text base
  1530. svg.Element.TextElementBase = function(node) {
  1531. this.base = svg.Element.RenderedElementBase;
  1532. this.base(node);
  1533. this.renderChildren = function(ctx) {
  1534. ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
  1535. }
  1536. this.getText = function() {
  1537. // OVERRIDE ME
  1538. }
  1539. this.measureText = function(ctx) {
  1540. var textToMeasure = svg.compressSpaces(this.getText());
  1541. if (!ctx.measureText) return textToMeasure.length * 10;
  1542. return ctx.measureText(textToMeasure).width;
  1543. }
  1544. }
  1545. svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase;
  1546. // tspan
  1547. svg.Element.tspan = function(node) {
  1548. this.base = svg.Element.TextElementBase;
  1549. this.base(node);
  1550. // TEXT ELEMENT
  1551. this.text = node.nodeType == 3 ? node.nodeValue : node.childNodes[0].nodeValue;
  1552. this.getText = function() {
  1553. return this.text;
  1554. }
  1555. }
  1556. svg.Element.tspan.prototype = new svg.Element.TextElementBase;
  1557. // tref
  1558. svg.Element.tref = function(node) {
  1559. this.base = svg.Element.TextElementBase;
  1560. this.base(node);
  1561. this.getText = function() {
  1562. var element = this.attribute('xlink:href').Definition.getDefinition();
  1563. if (element != null) return element.children[0].getText();
  1564. }
  1565. }
  1566. svg.Element.tref.prototype = new svg.Element.TextElementBase;
  1567. // a element
  1568. svg.Element.a = function(node) {
  1569. this.base = svg.Element.TextElementBase;
  1570. this.base(node);
  1571. this.hasText = true;
  1572. for (var i=0; i<node.childNodes.length; i++) {
  1573. if (node.childNodes[i].nodeType != 3) this.hasText = false;
  1574. }
  1575. // this might contain text
  1576. this.text = this.hasText ? node.childNodes[0].nodeValue : '';
  1577. this.getText = function() {
  1578. return this.text;
  1579. }
  1580. this.baseRenderChildren = this.renderChildren;
  1581. this.renderChildren = function(ctx) {
  1582. if (this.hasText) {
  1583. // render as text element
  1584. this.baseRenderChildren(ctx);
  1585. var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
  1586. svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y));
  1587. }
  1588. else {
  1589. // render as temporary group
  1590. var g = new svg.Element.g();
  1591. g.children = this.children;
  1592. g.parent = this;
  1593. g.render(ctx);
  1594. }
  1595. }
  1596. this.onclick = function() {
  1597. window.open(this.attribute('xlink:href').value);
  1598. }
  1599. this.onmousemove = function() {
  1600. svg.ctx.canvas.style.cursor = 'pointer';
  1601. }
  1602. }
  1603. svg.Element.a.prototype = new svg.Element.TextElementBase;
  1604. // image element
  1605. svg.Element.image = function(node) {
  1606. this.base = svg.Element.RenderedElementBase;
  1607. this.base(node);
  1608. svg.Images.push(this);
  1609. this.img = document.createElement('img');
  1610. this.loaded = false;
  1611. var that = this;
  1612. this.img.onload = function() { that.loaded = true; }
  1613. this.img.src = this.attribute('xlink:href').value;
  1614. this.renderChildren = function(ctx) {
  1615. var x = this.attribute('x').Length.toPixels('x');
  1616. var y = this.attribute('y').Length.toPixels('y');
  1617. var width = this.attribute('width').Length.toPixels('x');
  1618. var height = this.attribute('height').Length.toPixels('y');
  1619. if (width == 0 || height == 0) return;
  1620. ctx.save();
  1621. ctx.translate(x, y);
  1622. svg.AspectRatio(ctx,
  1623. this.attribute('preserveAspectRatio').value,
  1624. width,
  1625. this.img.width,
  1626. height,
  1627. this.img.height,
  1628. 0,
  1629. 0);
  1630. ctx.drawImage(this.img, 0, 0);
  1631. ctx.restore();
  1632. }
  1633. }
  1634. svg.Element.image.prototype = new svg.Element.RenderedElementBase;
  1635. // group element
  1636. svg.Element.g = function(node) {
  1637. this.base = svg.Element.RenderedElementBase;
  1638. this.base(node);
  1639. this.getBoundingBox = function() {
  1640. var bb = new svg.BoundingBox();
  1641. for (var i=0; i<this.children.length; i++) {
  1642. bb.addBoundingBox(this.children[i].getBoundingBox());
  1643. }
  1644. return bb;
  1645. };
  1646. }
  1647. svg.Element.g.prototype = new svg.Element.RenderedElementBase;
  1648. // symbol element
  1649. svg.Element.symbol = function(node) {
  1650. this.base = svg.Element.RenderedElementBase;
  1651. this.base(node);
  1652. this.baseSetContext = this.setContext;
  1653. this.setContext = function(ctx) {
  1654. this.baseSetContext(ctx);
  1655. // viewbox
  1656. if (this.attribute('viewBox').hasValue()) {
  1657. var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
  1658. var minX = viewBox[0];
  1659. var minY = viewBox[1];
  1660. width = viewBox[2];
  1661. height = viewBox[3];
  1662. svg.AspectRatio(ctx,
  1663. this.attribute('preserveAspectRatio').value,
  1664. this.attribute('width').Length.toPixels('x'),
  1665. width,
  1666. this.attribute('height').Length.toPixels('y'),
  1667. height,
  1668. minX,
  1669. minY);
  1670. svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
  1671. }
  1672. }
  1673. }
  1674. svg.Element.symbol.prototype = new svg.Element.RenderedElementBase;
  1675. // style element
  1676. svg.Element.style = function(node) {
  1677. this.base = svg.Element.ElementBase;
  1678. this.base(node);
  1679. var css = node.childNodes[0].nodeValue;
  1680. css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(\/\/.*)/gm, ''); // remove comments
  1681. css = svg.compressSpaces(css); // replace whitespace
  1682. var cssDefs = css.split('}');
  1683. for (var i=0; i<cssDefs.length; i++) {
  1684. if (svg.trim(cssDefs[i]) != '') {
  1685. var cssDef = cssDefs[i].split('{');
  1686. var cssClasses = cssDef[0].split(',');
  1687. var cssProps = cssDef[1].split(';');
  1688. for (var j=0; j<cssClasses.length; j++) {
  1689. var cssClass = svg.trim(cssClasses[j]);
  1690. if (cssClass != '') {
  1691. var props = {};
  1692. for (var k=0; k<cssProps.length; k++) {
  1693. var prop = cssProps[k].split(':');
  1694. var name = prop[0];
  1695. var value = prop[1];
  1696. if (name != null && value != null) {
  1697. props[svg.trim(prop[0])] = new svg.Property(svg.trim(prop[0]), svg.trim(prop[1]));
  1698. }
  1699. }
  1700. svg.Styles[cssClass] = props;
  1701. }
  1702. }
  1703. }
  1704. }
  1705. }
  1706. svg.Element.style.prototype = new svg.Element.ElementBase;
  1707. // use element
  1708. svg.Element.use = function(node) {
  1709. this.base = svg.Element.RenderedElementBase;
  1710. this.base(node);
  1711. this.baseSetContext = this.setContext;
  1712. this.setContext = function(ctx) {
  1713. this.baseSetContext(ctx);
  1714. if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0);
  1715. if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y'));
  1716. }
  1717. this.getDefinition = function() {
  1718. var element = this.attribute('xlink:href').Definition.getDefinition();
  1719. if (this.attribute('width').hasValue()) element.attribute('width', true).value = this.attribute('width').value;
  1720. if (this.attribute('height').hasValue()) element.attribute('height', true).value = this.attribute('height').value;
  1721. return element;
  1722. }
  1723. this.path = function(ctx) {
  1724. var element = this.getDefinition();
  1725. if (element != null) element.path(ctx);
  1726. }
  1727. this.renderChildren = function(ctx) {
  1728. var element = this.getDefinition();
  1729. if (element != null) element.render(ctx);
  1730. }
  1731. }
  1732. svg.Element.use.prototype = new svg.Element.RenderedElementBase;
  1733. // clip element
  1734. svg.Element.clipPath = function(node) {
  1735. this.base = svg.Element.ElementBase;
  1736. this.base(node);
  1737. this.apply = function(ctx) {
  1738. for (var i=0; i<this.children.length; i++) {
  1739. if (this.children[i].path) {
  1740. this.children[i].path(ctx);
  1741. ctx.clip();
  1742. }
  1743. }
  1744. }
  1745. }
  1746. svg.Element.clipPath.prototype = new svg.Element.ElementBase;
  1747. // title element, do nothing
  1748. svg.Element.title = function(node) {
  1749. }
  1750. svg.Element.title.prototype = new svg.Element.ElementBase;
  1751. // desc element, do nothing
  1752. svg.Element.desc = function(node) {
  1753. }
  1754. svg.Element.desc.prototype = new svg.Element.ElementBase;
  1755. svg.Element.MISSING = function(node) {
  1756. console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.');
  1757. }
  1758. svg.Element.MISSING.prototype = new svg.Element.ElementBase;
  1759. // element factory
  1760. svg.CreateElement = function(node) {
  1761. var className = node.nodeName.replace(/^[^:]+:/,'');
  1762. var e = null;
  1763. if (typeof(svg.Element[className]) != 'undefined') {
  1764. e = new svg.Element[className](node);
  1765. }
  1766. else {
  1767. e = new svg.Element.MISSING(node);
  1768. }
  1769. e.type = node.nodeName;
  1770. return e;
  1771. }
  1772. // load from url
  1773. svg.load = function(ctx, url) {
  1774. svg.loadXml(ctx, svg.ajax(url));
  1775. }
  1776. // load from xml
  1777. svg.loadXml = function(ctx, xml) {
  1778. svg.init(ctx);
  1779. var mapXY = function(p) {
  1780. var e = ctx.canvas;
  1781. while (e) {
  1782. p.x -= e.offsetLeft;
  1783. p.y -= e.offsetTop;
  1784. e = e.offsetParent;
  1785. }
  1786. if (window.scrollX) p.x += window.scrollX;
  1787. if (window.scrollY) p.y += window.scrollY;
  1788. return p;
  1789. }
  1790. // bind mouse
  1791. if (svg.opts == null || svg.opts['ignoreMouse'] != true) {
  1792. ctx.canvas.onclick = function(e) {
  1793. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  1794. svg.Mouse.onclick(p.x, p.y);
  1795. };
  1796. ctx.canvas.onmousemove = function(e) {
  1797. var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
  1798. svg.Mouse.onmousemove(p.x, p.y);
  1799. };
  1800. }
  1801. var dom = svg.parseXml(xml);
  1802. var e = svg.CreateElement(dom.documentElement);
  1803. // render loop
  1804. var isFirstRender = true;
  1805. var draw = function() {
  1806. if (svg.opts == null || svg.opts['ignoreDimensions'] != true) {
  1807. // set canvas size
  1808. if (e.style('width').hasValue()) {
  1809. ctx.canvas.width = e.style('width').Length.toPixels(ctx.canvas.parentNode.clientWidth);
  1810. }
  1811. if (e.style('height').hasValue()) {
  1812. ctx.canvas.height = e.style('height').Length.toPixels(ctx.canvas.parentNode.clientHeight);
  1813. }
  1814. }
  1815. svg.ViewPort.SetCurrent(ctx.canvas.clientWidth, ctx.canvas.clientHeight);
  1816. if (svg.opts != null && svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX'];
  1817. if (svg.opts != null && svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY'];
  1818. if (svg.opts != null && svg.opts['scaleWidth'] != null && svg.opts['scaleHeight'] != null) {
  1819. e.attribute('width', true).value = svg.opts['scaleWidth'];
  1820. e.attribute('height', true).value = svg.opts['scaleHeight'];
  1821. e.attribute('viewBox', true).value = '0 0 ' + ctx.canvas.clientWidth + ' ' + ctx.canvas.clientHeight;
  1822. e.attribute('preserveAspectRatio', true).value = 'none';
  1823. }
  1824. // clear and render
  1825. if (svg.opts == null || svg.opts['ignoreClear'] != true) {
  1826. ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
  1827. }
  1828. e.render(ctx);
  1829. if (isFirstRender) {
  1830. isFirstRender = false;
  1831. if (svg.opts != null && typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback']();
  1832. }
  1833. }
  1834. var waitingForImages = true;
  1835. if (svg.ImagesLoaded()) {
  1836. waitingForImages = false;
  1837. draw();
  1838. }
  1839. svg.intervalID = setInterval(function() {
  1840. var needUpdate = false;
  1841. if (waitingForImages && svg.ImagesLoaded()) {
  1842. waitingForImages = false;
  1843. needUpdate = true;
  1844. }
  1845. // need update from mouse events?
  1846. if (svg.opts == null || svg.opts['ignoreMouse'] != true) {
  1847. needUpdate = needUpdate | svg.Mouse.hasEvents();
  1848. }
  1849. // need update from animations?
  1850. if (svg.opts == null || svg.opts['ignoreAnimation'] != true) {
  1851. for (var i=0; i<svg.Animations.length; i++) {
  1852. needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE);
  1853. }
  1854. }
  1855. // need update from redraw?
  1856. if (svg.opts != null && typeof(svg.opts['forceRedraw']) == 'function') {
  1857. if (svg.opts['forceRedraw']() == true) needUpdate = true;
  1858. }
  1859. // render if needed
  1860. if (needUpdate) {
  1861. draw();
  1862. svg.Mouse.runEvents(); // run and clear our events
  1863. }
  1864. }, 1000 / svg.FRAMERATE);
  1865. }
  1866. svg.stop = function() {
  1867. if (svg.intervalID) {
  1868. clearInterval(svg.intervalID);
  1869. }
  1870. }
  1871. svg.Mouse = new (function() {
  1872. this.events = [];
  1873. this.hasEvents = function() { return this.events.length != 0; }
  1874. this.onclick = function(x, y) {
  1875. this.events.push({ type: 'onclick', x: x, y: y,
  1876. run: function(e) { if (e.onclick) e.onclick(); }
  1877. });
  1878. }
  1879. this.onmousemove = function(x, y) {
  1880. this.events.push({ type: 'onmousemove', x: x, y: y,
  1881. run: function(e) { if (e.onmousemove) e.onmousemove(); }
  1882. });
  1883. }
  1884. this.eventElements = [];
  1885. this.checkPath = function(element, ctx) {
  1886. for (var i=0; i<this.events.length; i++) {
  1887. var e = this.events[i];
  1888. if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;
  1889. }
  1890. }
  1891. this.checkBoundingBox = function(element, bb) {
  1892. for (var i=0; i<this.events.length; i++) {
  1893. var e = this.events[i];
  1894. if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;
  1895. }
  1896. }
  1897. this.runEvents = function() {
  1898. svg.ctx.canvas.style.cursor = '';
  1899. for (var i=0; i<this.events.length; i++) {
  1900. var e = this.events[i];
  1901. var element = this.eventElements[i];
  1902. while (element) {
  1903. e.run(element);
  1904. element = element.parent;
  1905. }
  1906. }
  1907. // done running, clear
  1908. this.events = [];
  1909. this.eventElements = [];
  1910. }
  1911. });
  1912. return svg;
  1913. }
  1914. })();
  1915. if (CanvasRenderingContext2D) {
  1916. CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh) {
  1917. canvg(this.canvas, s, {
  1918. ignoreMouse: true,
  1919. ignoreAnimation: true,
  1920. ignoreDimensions: true,
  1921. ignoreClear: true,
  1922. offsetX: dx,
  1923. offsetY: dy,
  1924. scaleWidth: dw,
  1925. scaleHeight: dh
  1926. });
  1927. }
  1928. }
  1929. /**
  1930. * A class to parse color values
  1931. * @author Stoyan Stefanov <sstoo@gmail.com>
  1932. * @link http://www.phpied.com/rgb-color-parser-in-javascript/
  1933. * @license Use it if you like it
  1934. */
  1935. function RGBColor(color_string)
  1936. {
  1937. this.ok = false;
  1938. // strip any leading #
  1939. if (color_string.charAt(0) == '#') { // remove # if any
  1940. color_string = color_string.substr(1,6);
  1941. }
  1942. color_string = color_string.replace(/ /g,'');
  1943. color_string = color_string.toLowerCase();
  1944. // before getting into regexps, try simple matches
  1945. // and overwrite the input
  1946. var simple_colors = {
  1947. aliceblue: 'f0f8ff',
  1948. antiquewhite: 'faebd7',
  1949. aqua: '00ffff',
  1950. aquamarine: '7fffd4',
  1951. azure: 'f0ffff',
  1952. beige: 'f5f5dc',
  1953. bisque: 'ffe4c4',
  1954. black: '000000',
  1955. blanchedalmond: 'ffebcd',
  1956. blue: '0000ff',
  1957. blueviolet: '8a2be2',
  1958. brown: 'a52a2a',
  1959. burlywood: 'deb887',
  1960. cadetblue: '5f9ea0',
  1961. chartreuse: '7fff00',
  1962. chocolate: 'd2691e',
  1963. coral: 'ff7f50',
  1964. cornflowerblue: '6495ed',
  1965. cornsilk: 'fff8dc',
  1966. crimson: 'dc143c',
  1967. cyan: '00ffff',
  1968. darkblue: '00008b',
  1969. darkcyan: '008b8b',
  1970. darkgoldenrod: 'b8860b',
  1971. darkgray: 'a9a9a9',
  1972. darkgreen: '006400',
  1973. darkkhaki: 'bdb76b',
  1974. darkmagenta: '8b008b',
  1975. darkolivegreen: '556b2f',
  1976. darkorange: 'ff8c00',
  1977. darkorchid: '9932cc',
  1978. darkred: '8b0000',
  1979. darksalmon: 'e9967a',
  1980. darkseagreen: '8fbc8f',
  1981. darkslateblue: '483d8b',
  1982. darkslategray: '2f4f4f',
  1983. darkturquoise: '00ced1',
  1984. darkviolet: '9400d3',
  1985. deeppink: 'ff1493',
  1986. deepskyblue: '00bfff',
  1987. dimgray: '696969',
  1988. dodgerblue: '1e90ff',
  1989. feldspar: 'd19275',
  1990. firebrick: 'b22222',
  1991. floralwhite: 'fffaf0',
  1992. forestgreen: '228b22',
  1993. fuchsia: 'ff00ff',
  1994. gainsboro: 'dcdcdc',
  1995. ghostwhite: 'f8f8ff',
  1996. gold: 'ffd700',
  1997. goldenrod: 'daa520',
  1998. gray: '808080',
  1999. green: '008000',
  2000. greenyellow: 'adff2f',
  2001. honeydew: 'f0fff0',
  2002. hotpink: 'ff69b4',
  2003. indianred : 'cd5c5c',
  2004. indigo : '4b0082',
  2005. ivory: 'fffff0',
  2006. khaki: 'f0e68c',
  2007. lavender: 'e6e6fa',
  2008. lavenderblush: 'fff0f5',
  2009. lawngreen: '7cfc00',
  2010. lemonchiffon: 'fffacd',
  2011. lightblue: 'add8e6',
  2012. lightcoral: 'f08080',
  2013. lightcyan: 'e0ffff',
  2014. lightgoldenrodyellow: 'fafad2',
  2015. lightgrey: 'd3d3d3',
  2016. lightgreen: '90ee90',
  2017. lightpink: 'ffb6c1',
  2018. lightsalmon: 'ffa07a',
  2019. lightseagreen: '20b2aa',
  2020. lightskyblue: '87cefa',
  2021. lightslateblue: '8470ff',
  2022. lightslategray: '778899',
  2023. lightsteelblue: 'b0c4de',
  2024. lightyellow: 'ffffe0',
  2025. lime: '00ff00',
  2026. limegreen: '32cd32',
  2027. linen: 'faf0e6',
  2028. magenta: 'ff00ff',
  2029. maroon: '800000',
  2030. mediumaquamarine: '66cdaa',
  2031. mediumblue: '0000cd',
  2032. mediumorchid: 'ba55d3',
  2033. mediumpurple: '9370d8',
  2034. mediumseagreen: '3cb371',
  2035. mediumslateblue: '7b68ee',
  2036. mediumspringgreen: '00fa9a',
  2037. mediumturquoise: '48d1cc',
  2038. mediumvioletred: 'c71585',
  2039. midnightblue: '191970',
  2040. mintcream: 'f5fffa',
  2041. mistyrose: 'ffe4e1',
  2042. moccasin: 'ffe4b5',
  2043. navajowhite: 'ffdead',
  2044. navy: '000080',
  2045. oldlace: 'fdf5e6',
  2046. olive: '808000',
  2047. olivedrab: '6b8e23',
  2048. orange: 'ffa500',
  2049. orangered: 'ff4500',
  2050. orchid: 'da70d6',
  2051. palegoldenrod: 'eee8aa',
  2052. palegreen: '98fb98',
  2053. paleturquoise: 'afeeee',
  2054. palevioletred: 'd87093',
  2055. papayawhip: 'ffefd5',
  2056. peachpuff: 'ffdab9',
  2057. peru: 'cd853f',
  2058. pink: 'ffc0cb',
  2059. plum: 'dda0dd',
  2060. powderblue: 'b0e0e6',
  2061. purple: '800080',
  2062. red: 'ff0000',
  2063. rosybrown: 'bc8f8f',
  2064. royalblue: '4169e1',
  2065. saddlebrown: '8b4513',
  2066. salmon: 'fa8072',
  2067. sandybrown: 'f4a460',
  2068. seagreen: '2e8b57',
  2069. seashell: 'fff5ee',
  2070. sienna: 'a0522d',
  2071. silver: 'c0c0c0',
  2072. skyblue: '87ceeb',
  2073. slateblue: '6a5acd',
  2074. slategray: '708090',
  2075. snow: 'fffafa',
  2076. springgreen: '00ff7f',
  2077. steelblue: '4682b4',
  2078. tan: 'd2b48c',
  2079. teal: '008080',
  2080. thistle: 'd8bfd8',
  2081. tomato: 'ff6347',
  2082. turquoise: '40e0d0',
  2083. violet: 'ee82ee',
  2084. violetred: 'd02090',
  2085. wheat: 'f5deb3',
  2086. white: 'ffffff',
  2087. whitesmoke: 'f5f5f5',
  2088. yellow: 'ffff00',
  2089. yellowgreen: '9acd32'
  2090. };
  2091. for (var key in simple_colors) {
  2092. if (color_string == key) {
  2093. color_string = simple_colors[key];
  2094. }
  2095. }
  2096. // emd of simple type-in colors
  2097. // array of color definition objects
  2098. var color_defs = [
  2099. {
  2100. re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
  2101. example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
  2102. process: function (bits){
  2103. return [
  2104. parseInt(bits[1]),
  2105. parseInt(bits[2]),
  2106. parseInt(bits[3])
  2107. ];
  2108. }
  2109. },
  2110. {
  2111. re: /^(\w{2})(\w{2})(\w{2})$/,
  2112. example: ['#00ff00', '336699'],
  2113. process: function (bits){
  2114. return [
  2115. parseInt(bits[1], 16),
  2116. parseInt(bits[2], 16),
  2117. parseInt(bits[3], 16)
  2118. ];
  2119. }
  2120. },
  2121. {
  2122. re: /^(\w{1})(\w{1})(\w{1})$/,
  2123. example: ['#fb0', 'f0f'],
  2124. process: function (bits){
  2125. return [
  2126. parseInt(bits[1] + bits[1], 16),
  2127. parseInt(bits[2] + bits[2], 16),
  2128. parseInt(bits[3] + bits[3], 16)
  2129. ];
  2130. }
  2131. }
  2132. ];
  2133. // search through the definitions to find a match
  2134. for (var i = 0; i < color_defs.length; i++) {
  2135. var re = color_defs[i].re;
  2136. var processor = color_defs[i].process;
  2137. var bits = re.exec(color_string);
  2138. if (bits) {
  2139. channels = processor(bits);
  2140. this.r = channels[0];
  2141. this.g = channels[1];
  2142. this.b = channels[2];
  2143. this.ok = true;
  2144. }
  2145. }
  2146. // validate/cleanup values
  2147. this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
  2148. this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
  2149. this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
  2150. // some getters
  2151. this.toRGB = function () {
  2152. return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
  2153. }
  2154. this.toHex = function () {
  2155. var r = this.r.toString(16);
  2156. var g = this.g.toString(16);
  2157. var b = this.b.toString(16);
  2158. if (r.length == 1) r = '0' + r;
  2159. if (g.length == 1) g = '0' + g;
  2160. if (b.length == 1) b = '0' + b;
  2161. return '#' + r + g + b;
  2162. }
  2163. // help
  2164. this.getHelpXML = function () {
  2165. var examples = new Array();
  2166. // add regexps
  2167. for (var i = 0; i < color_defs.length; i++) {
  2168. var example = color_defs[i].example;
  2169. for (var j = 0; j < example.length; j++) {
  2170. examples[examples.length] = example[j];
  2171. }
  2172. }
  2173. // add type-in colors
  2174. for (var sc in simple_colors) {
  2175. examples[examples.length] = sc;
  2176. }
  2177. var xml = document.createElement('ul');
  2178. xml.setAttribute('id', 'rgbcolor-examples');
  2179. for (var i = 0; i < examples.length; i++) {
  2180. try {
  2181. var list_item = document.createElement('li');
  2182. var list_color = new RGBColor(examples[i]);
  2183. var example_div = document.createElement('div');
  2184. example_div.style.cssText =
  2185. 'margin: 3px; '
  2186. + 'border: 1px solid black; '
  2187. + 'background:' + list_color.toHex() + '; '
  2188. + 'color:' + list_color.toHex()
  2189. ;
  2190. example_div.appendChild(document.createTextNode('test'));
  2191. var list_item_value = document.createTextNode(
  2192. ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()
  2193. );
  2194. list_item.appendChild(example_div);
  2195. list_item.appendChild(list_item_value);
  2196. xml.appendChild(list_item);
  2197. } catch(e){}
  2198. }
  2199. return xml;
  2200. }
  2201. }