Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

3249 rindas
115 KiB

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