source: other-projects/nz-flag-design/trunk/main-form/lib/canvg/canvg.js@ 29567

Last change on this file since 29567 was 29567, checked in by davidb, 9 years ago

Addition of further library (to support exporting SVG to PNG) on the iterative-design page

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