4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-draw-engine-Svg'>/**
19 </span> * @class Ext.draw.engine.Svg
20 * @extends Ext.draw.Surface
21 * Provides specific methods to draw with SVG.
23 Ext.define('Ext.draw.engine.Svg', {
25 /* Begin Definitions */
27 extend: 'Ext.draw.Surface',
29 requires: ['Ext.draw.Draw', 'Ext.draw.Sprite', 'Ext.draw.Matrix', 'Ext.core.Element'],
37 xlink: "http:/" + "/www.w3.org/1999/xlink",
40 radius: "r",
41 radiusX: "rx",
42 radiusY: "ry",
44 lineWidth: "stroke-width",
45 fillOpacity: "fill-opacity",
46 strokeOpacity: "stroke-opacity",
47 strokeLinejoin: "stroke-linejoin"
55 fill: "none",
57 "stroke-width": null,
59 "fill-opacity": null,
60 "stroke-opacity": null
67 fill: "none",
69 "stroke-width": null,
71 "fill-opacity": null,
72 "stroke-opacity": null
81 fill: "none",
83 "stroke-width": null,
85 "fill-opacity": null,
86 "stroke-opacity": null
91 "text-anchor": "start",
92 "font-family": null,
93 "font-size": null,
94 "font-weight": null,
95 "font-style": null,
96 fill: "#000",
98 "stroke-width": null,
100 "fill-opacity": null,
101 "stroke-opacity": null
105 fill: "none",
107 "stroke-width": null,
109 "fill-opacity": null,
110 "stroke-opacity": null
117 preserveAspectRatio: "none",
122 createSvgElement: function(type, attrs) {
123 var el = this.domRef.createElementNS("http:/" + "/www.w3.org/2000/svg", type),
127 el.setAttribute(key, String(attrs[key]));
133 createSpriteElement: function(sprite) {
134 // Create svg element and append to the DOM.
135 var el = this.createSvgElement(sprite.type);
138 el.style.webkitTapHighlightColor = "rgba(0,0,0,0)";
140 sprite.el = Ext.get(el);
141 this.applyZIndex(sprite); //performs the insertion
142 sprite.matrix = Ext.create('Ext.draw.Matrix');
147 sprite.fireEvent("render", sprite);
151 getBBox: function (sprite, isWithoutTransform) {
152 var realPath = this["getPath" + sprite.type](sprite);
153 if (isWithoutTransform) {
154 sprite.bbox.plain = sprite.bbox.plain || Ext.draw.Draw.pathDimensions(realPath);
155 return sprite.bbox.plain;
157 sprite.bbox.transform = sprite.bbox.transform || Ext.draw.Draw.pathDimensions(Ext.draw.Draw.mapPath(realPath, sprite.matrix));
158 return sprite.bbox.transform;
161 getBBoxText: function (sprite) {
163 bb, height, width, i, ln, el;
165 if (sprite && sprite.el) {
171 // Firefox 3.0.x plays badly here
173 bbox = {x: bbox.x, y: Infinity, width: 0, height: 0};
174 ln = el.getNumberOfChars();
175 for (i = 0; i < ln; i++) {
176 bb = el.getExtentOfChar(i);
177 bbox.y = Math.min(bb.y, bbox.y);
178 height = bb.y + bb.height - bbox.y;
179 bbox.height = Math.max(bbox.height, height);
180 width = bb.x + bb.width - bbox.x;
181 bbox.width = Math.max(bbox.width, width);
188 Ext.get(this.el).hide();
192 Ext.get(this.el).show();
195 hidePrim: function(sprite) {
196 this.addCls(sprite, Ext.baseCSSPrefix + 'hide-visibility');
199 showPrim: function(sprite) {
200 this.removeCls(sprite, Ext.baseCSSPrefix + 'hide-visibility');
203 getDefs: function() {
204 return this._defs || (this._defs = this.createSvgElement("defs"));
207 transform: function(sprite) {
209 matrix = Ext.create('Ext.draw.Matrix'),
210 transforms = sprite.transformations,
211 transformsLength = transforms.length,
215 for (; i < transformsLength; i++) {
216 transform = transforms[i];
217 type = transform.type;
218 if (type == "translate") {
219 matrix.translate(transform.x, transform.y);
221 else if (type == "rotate") {
222 matrix.rotate(transform.degrees, transform.x, transform.y);
224 else if (type == "scale") {
225 matrix.scale(transform.x, transform.y, transform.centerX, transform.centerY);
228 sprite.matrix = matrix;
229 sprite.el.set({transform: matrix.toSvg()});
232 setSize: function(w, h) {
246 me.callParent([w, h]);
249 <span id='Ext-draw-engine-Svg-method-getRegion'> /**
250 </span> * Get the region for the surface's canvas area
251 * @returns {Ext.util.Region}
253 getRegion: function() {
254 // Mozilla requires using the background rect because the svg element returns an
255 // incorrect region. Webkit gives no region for the rect and must use the svg element.
256 var svgXY = this.el.getXY(),
257 rectXY = this.bgRect.getXY(),
259 x = max(svgXY[0], rectXY[0]),
260 y = max(svgXY[1], rectXY[1]);
264 right: x + this.width,
265 bottom: y + this.height
269 onRemove: function(sprite) {
274 this.callParent(arguments);
277 setViewBox: function(x, y, width, height) {
278 if (isFinite(x) && isFinite(y) && isFinite(width) && isFinite(height)) {
279 this.callParent(arguments);
280 this.el.dom.setAttribute("viewBox", [x, y, width, height].join(" "));
284 render: function (container) {
287 var width = me.width || 10,
288 height = me.height || 10,
289 el = me.createSvgElement('svg', {
290 xmlns: "http:/" + "/www.w3.org/2000/svg",
297 // Create a rect that is always the same size as the svg root; this serves 2 purposes:
298 // (1) It allows mouse events to be fired over empty areas in Webkit, and (2) we can
299 // use it rather than the svg element for retrieving the correct client rect of the
300 // surface in Mozilla (see https://bugzilla.mozilla.org/show_bug.cgi?id=530985)
301 bgRect = me.createSvgElement("rect", {
302 width: "100%",
303 height: "100%",
304 fill: "#000",
305 stroke: "none",
311 // Rect that we will show/hide to fix old WebKit bug with rendering issues.
312 webkitRect = me.createSvgElement("rect", {
315 width: "110%",
316 height: "110%",
317 fill: "none",
318 stroke: "#000"
321 el.appendChild(defs);
323 el.appendChild(webkitRect);
325 el.appendChild(bgRect);
326 container.appendChild(el);
328 me.bgRect = Ext.get(bgRect);
330 me.webkitRect = Ext.get(webkitRect);
331 me.webkitRect.hide();
335 mouseup: me.onMouseUp,
336 mousedown: me.onMouseDown,
337 mouseover: me.onMouseOver,
338 mouseout: me.onMouseOut,
339 mousemove: me.onMouseMove,
340 mouseenter: me.onMouseEnter,
341 mouseleave: me.onMouseLeave,
349 onMouseEnter: function(e) {
350 if (this.el.parent().getRegion().contains(e.getPoint())) {
351 this.fireEvent('mouseenter', e);
356 onMouseLeave: function(e) {
357 if (!this.el.parent().getRegion().contains(e.getPoint())) {
358 this.fireEvent('mouseleave', e);
361 // @private - Normalize a delegated single event from the main container to each sprite and sprite group
362 processEvent: function(name, e) {
363 var target = e.getTarget(),
364 surface = this.surface,
367 this.fireEvent(name, e);
368 // We wrap text types in a tspan, sprite is the parent.
369 if (target.nodeName == "tspan" && target.parentNode) {
370 target = target.parentNode;
372 sprite = this.items.get(target.id);
374 sprite.fireEvent(name, sprite, e);
378 /* @private - Wrap SVG text inside a tspan to allow for line wrapping. In addition this normallizes
379 * the baseline for text the vertical middle of the text to be the same as VML.
381 tuneText: function (sprite, attrs) {
382 var el = sprite.el.dom,
384 height, tspan, text, i, ln, texts, factor;
386 if (attrs.hasOwnProperty("text")) {
387 tspans = this.setText(sprite, attrs.text);
389 // Normalize baseline via a DY shift of first tspan. Shift other rows by height * line height (1.2)
391 height = this.getBBoxText(sprite).height;
392 for (i = 0, ln = tspans.length; i < ln; i++) {
393 // The text baseline for FireFox 3.0 and 3.5 is different than other SVG implementations
394 // so we are going to normalize that here
395 factor = (Ext.isFF3_0 || Ext.isFF3_5) ? 2 : 4;
396 tspans[i].setAttribute("dy", i ? height * 1.2 : height / factor);
402 setText: function(sprite, textString) {
405 x = el.getAttribute("x"),
407 height, tspan, text, i, ln, texts;
409 while (el.firstChild) {
410 el.removeChild(el.firstChild);
412 // Wrap each row into tspan to emulate rows
413 texts = String(textString).split("\n");
414 for (i = 0, ln = texts.length; i < ln; i++) {
417 tspan = me.createSvgElement("tspan");
418 tspan.appendChild(document.createTextNode(Ext.htmlDecode(text)));
419 tspan.setAttribute("x", x);
420 el.appendChild(tspan);
427 renderAll: function() {
428 this.items.each(this.renderItem, this);
431 renderItem: function (sprite) {
436 this.createSpriteElement(sprite);
438 if (sprite.zIndexDirty) {
439 this.applyZIndex(sprite);
442 this.applyAttrs(sprite);
443 this.applyTransformations(sprite);
447 redraw: function(sprite) {
448 sprite.dirty = sprite.zIndexDirty = true;
449 this.renderItem(sprite);
452 applyAttrs: function (sprite) {
455 group = sprite.group,
457 groups, i, ln, attrs, font, key, style, name, rect;
460 groups = [].concat(group);
462 for (i = 0; i < ln; i++) {
464 me.getGroup(group).add(sprite);
468 attrs = me.scrubAttrs(sprite) || {};
470 // if (sprite.dirtyPath) {
471 sprite.bbox.plain = 0;
472 sprite.bbox.transform = 0;
473 if (sprite.type == "circle" || sprite.type == "ellipse") {
474 attrs.cx = attrs.cx || attrs.x;
475 attrs.cy = attrs.cy || attrs.y;
477 else if (sprite.type == "rect") {
478 attrs.rx = attrs.ry = attrs.r;
480 else if (sprite.type == "path" && attrs.d) {
481 attrs.d = Ext.draw.Draw.pathToString(Ext.draw.Draw.pathToAbsolute(attrs.d));
484 sprite.dirtyPath = false;
490 if (attrs['clip-rect']) {
491 me.setClip(sprite, attrs);
492 delete attrs['clip-rect'];
494 if (sprite.type == 'text' && attrs.font && sprite.dirtyFont) {
495 el.set({ style: "font: " + attrs.font});
496 sprite.dirtyFont = false;
498 if (sprite.type == "image") {
499 el.dom.setAttributeNS(me.xlink, "href", attrs.src);
501 Ext.applyIf(attrs, me.minDefaults[sprite.type]);
503 if (sprite.dirtyHidden) {
504 (sattr.hidden) ? me.hidePrim(sprite) : me.showPrim(sprite);
505 sprite.dirtyHidden = false;
508 if (attrs.hasOwnProperty(key) && attrs[key] != null) {
509 el.dom.setAttribute(key, attrs[key]);
512 if (sprite.type == 'text') {
513 me.tuneText(sprite, attrs);
522 sprite.dirty = false;
525 // Refreshing the view to fix bug EXTJSIV-1: rendering issue in old Safari 3
526 me.webkitRect.show();
527 setTimeout(function () {
528 me.webkitRect.hide();
533 setClip: function(sprite, params) {
535 rect = params["clip-rect"],
539 sprite.clip.parentNode.parentNode.removeChild(sprite.clip.parentNode);
541 clipEl = me.createSvgElement('clipPath');
542 clipPath = me.createSvgElement('rect');
543 clipEl.id = Ext.id(null, 'ext-clip-');
544 clipPath.setAttribute("x", rect.x);
545 clipPath.setAttribute("y", rect.y);
546 clipPath.setAttribute("width", rect.width);
547 clipPath.setAttribute("height", rect.height);
548 clipEl.appendChild(clipPath);
549 me.getDefs().appendChild(clipEl);
550 sprite.el.dom.setAttribute("clip-path", "url(#" + clipEl.id + ")");
551 sprite.clip = clipPath;
553 // if (!attrs[key]) {
554 // var clip = Ext.getDoc().dom.getElementById(sprite.el.getAttribute("clip-path").replace(/(^url\(#|\)$)/g, ""));
555 // clip && clip.parentNode.removeChild(clip);
556 // sprite.el.setAttribute("clip-path", "");
557 // delete attrss.clip;
561 <span id='Ext-draw-engine-Svg-method-applyZIndex'> /**
562 </span> * Insert or move a given sprite's element to the correct place in the DOM list for its zIndex
563 * @param {Ext.draw.Sprite} sprite
565 applyZIndex: function(sprite) {
566 var idx = this.normalizeSpriteCollection(sprite),
569 if (this.el.dom.childNodes[idx + 2] !== el.dom) { //shift by 2 to account for defs and bg rect
571 // Find the first previous sprite which has its DOM element created already
573 prevEl = this.items.getAt(--idx).el;
574 } while (!prevEl && idx > 0);
576 el.insertAfter(prevEl || this.bgRect);
578 sprite.zIndexDirty = false;
581 createItem: function (config) {
582 var sprite = Ext.create('Ext.draw.Sprite', config);
583 sprite.surface = this;
587 addGradient: function(gradient) {
588 gradient = Ext.draw.Draw.parseGradient(gradient);
589 var ln = gradient.stops.length,
590 vector = gradient.vector,
595 if (gradient.type == "linear") {
596 gradientEl = this.createSvgElement("linearGradient");
597 gradientEl.setAttribute("x1", vector[0]);
598 gradientEl.setAttribute("y1", vector[1]);
599 gradientEl.setAttribute("x2", vector[2]);
600 gradientEl.setAttribute("y2", vector[3]);
603 gradientEl = this.createSvgElement("radialGradient");
604 gradientEl.setAttribute("cx", gradient.centerX);
605 gradientEl.setAttribute("cy", gradient.centerY);
606 gradientEl.setAttribute("r", gradient.radius);
607 if (Ext.isNumber(gradient.focalX) && Ext.isNumber(gradient.focalY)) {
608 gradientEl.setAttribute("fx", gradient.focalX);
609 gradientEl.setAttribute("fy", gradient.focalY);
612 gradientEl.id = gradient.id;
613 this.getDefs().appendChild(gradientEl);
615 for (i = 0; i < ln; i++) {
616 stop = gradient.stops[i];
617 stopEl = this.createSvgElement("stop");
618 stopEl.setAttribute("offset", stop.offset + "%");
619 stopEl.setAttribute("stop-color", stop.color);
620 stopEl.setAttribute("stop-opacity",stop.opacity);
621 gradientEl.appendChild(stopEl);
625 <span id='Ext-draw-engine-Svg-method-hasCls'> /**
626 </span> * Checks if the specified CSS class exists on this element's DOM node.
627 * @param {String} className The CSS class to check for
628 * @return {Boolean} True if the class exists, else false
630 hasCls: function(sprite, className) {
631 return className && (' ' + (sprite.el.dom.getAttribute('class') || '') + ' ').indexOf(' ' + className + ' ') != -1;
634 addCls: function(sprite, className) {
640 curCls = el.getAttribute('class') || '';
641 // Separate case is for speed
642 if (!Ext.isArray(className)) {
643 if (typeof className == 'string' && !this.hasCls(sprite, className)) {
644 el.set({ 'class': curCls + ' ' + className });
648 for (i = 0, len = className.length; i < len; i++) {
650 if (typeof v == 'string' && (' ' + curCls + ' ').indexOf(' ' + v + ' ') == -1) {
655 el.set({ 'class': ' ' + cls.join(' ') });
660 removeCls: function(sprite, className) {
663 curCls = el.getAttribute('class') || '',
664 i, idx, len, cls, elClasses;
665 if (!Ext.isArray(className)){
666 className = [className];
669 elClasses = curCls.replace(me.trimRe, ' ').split(me.spacesRe);
670 for (i = 0, len = className.length; i < len; i++) {
672 if (typeof cls == 'string') {
673 cls = cls.replace(me.trimRe, '');
674 idx = Ext.Array.indexOf(elClasses, cls);
676 elClasses.splice(idx, 1);
680 el.set({ 'class': elClasses.join(' ') });
684 destroy: function() {