SVG implementation for ART
(function(){
var NS = 'http://www.w3.org/2000/svg', XLINK = 'http://www.w3.org/1999/xlink', XML = 'http://www.w3.org/XML/1998/namespace',
UID = 0,
createElement = function(tag){
return document.createElementNS(NS, tag);
};
var ua = navigator && navigator.userAgent,
hasBaseline = !(/opera|safari|ie/i).test(ua) || (/chrome/i).test(ua);
SVG Base Class
ART.SVG = new Class({
Extends: ART.Element,
Implements: ART.Container,
initialize: function(width, height){
var element = this.element = createElement('svg');
element.setAttribute('xmlns', NS);
element.setAttribute('version', 1.1);
var defs = this.defs = createElement('defs');
element.appendChild(defs);
if (width != null && height != null) this.resize(width, height);
},
resize: function(width, height){
var element = this.element;
element.setAttribute('width', width);
element.setAttribute('height', height);
this.width = width;
this.height = height;
return this;
},
toElement: function(){
return this.element;
}
});
SVG Element Class
ART.SVG.Element = new Class({
Extends: ART.Element,
Implements: ART.Transform,
initialize: function(tag){
this.uid = String.uniqueID();
var element = this.element = createElement(tag);
element.setAttribute('id', 'e' + this.uid);
},
transforms
_transform: function(){
var m = this;
this.element.setAttribute('transform', 'matrix(' + [m.xx, m.yx, m.xy, m.yy, m.x, m.y] + ')');
},
blend: function(opacity){
this.element.setAttribute('opacity', opacity);
return this;
},
visibility
hide: function(){
this.element.setAttribute('display', 'none');
return this;
},
show: function(){
this.element.setAttribute('display', '');
return this;
},
interaction
indicate: function(cursor, tooltip){
var element = this.element;
if (cursor) this.element.style.cursor = cursor;
if (tooltip){
var title = this.titleElement;
if (title){
title.firstChild.nodeValue = tooltip;
} else {
this.titleElement = title = createElement('title');
title.appendChild(document.createTextNode(tooltip));
element.insertBefore(title, element.firstChild);
}
}
return this;
}
});
SVG Group Class
ART.SVG.Group = new Class({
Extends: ART.SVG.Element,
Implements: ART.Container,
initialize: function(width, height){
this.parent('g');
this.width = width;
this.height = height;
this.defs = createElement('defs');
this.element.appendChild(this.defs);
}
});
SVG Base Shape Class
ART.SVG.Base = new Class({
Extends: ART.SVG.Element,
initialize: function(tag){
this.parent(tag);
this.fill();
this.stroke();
},
insertions
inject: function(container){
this.eject();
this.container = container;
this._injectBrush('fill');
this._injectBrush('stroke');
this.parent(container);
return this;
},
eject: function(){
if (this.container){
this.parent();
this._ejectBrush('fill');
this._ejectBrush('stroke');
this.container = null;
}
return this;
},
_injectBrush: function(type){
if (!this.container) return;
var brush = this[type + 'Brush'];
if (brush) this.container.defs.appendChild(brush);
},
_ejectBrush: function(type){
if (!this.container) return;
var brush = this[type + 'Brush'];
if (brush) this.container.defs.removeChild(brush);
},
styles
_createBrush: function(type, tag){
this._ejectBrush(type);
var brush = createElement(tag);
this[type + 'Brush'] = brush;
var id = type + '-brush-e' + this.uid;
brush.setAttribute('id', id);
this._injectBrush(type);
this.element.setAttribute(type, 'url(#' + id + ')');
return brush;
},
_createGradient: function(type, style, stops){
var gradient = this._createBrush(type, style);
var addColor = function(offset, color){
color = Color.detach(color);
var stop = createElement('stop');
stop.setAttribute('offset', offset);
stop.setAttribute('stop-color', color[0]);
stop.setAttribute('stop-opacity', color[1]);
gradient.appendChild(stop);
};
Enumerate stops, assumes offsets are enumerated in order TODO: Sort. Chrome doesn’t always enumerate in expected order but requires stops to be specified in order.
if ('length' in stops) for (var i = 0, l = stops.length - 1; i <= l; i++) addColor(i / l, stops[i]);
else for (var offset in stops) addColor(offset, stops[offset]);
gradient.setAttribute('spreadMethod', 'reflect'); // Closer to the VML gradient
this.element.removeAttribute('fill-opacity');
return gradient;
},
_setColor: function(type, color){
this._ejectBrush(type);
this[type + 'Brush'] = null;
var element = this.element;
if (color == null){
element.setAttribute(type, 'none');
element.removeAttribute(type + '-opacity');
} else {
color = Color.detach(color);
element.setAttribute(type, color[0]);
element.setAttribute(type + '-opacity', color[1]);
}
},
fill: function(color){
if (arguments.length > 1) this.fillLinear(arguments);
else this._setColor('fill', color);
return this;
},
fillRadial: function(stops, focusX, focusY, radiusX, radiusY, centerX, centerY){
var gradient = this._createGradient('fill', 'radialGradient', stops);
gradient.setAttribute('gradientUnits', 'userSpaceOnUse');
if (focusX == null) focusX = (this.left || 0) + (this.width || 0) * 0.5;
if (focusY == null) focusY = (this.top || 0) + (this.height || 0) * 0.5;
if (radiusY == null) radiusY = radiusX || (this.height * 0.5) || 0;
if (radiusX == null) radiusX = (this.width || 0) * 0.5;
if (centerX == null) centerX = focusX;
if (centerY == null) centerY = focusY;
var ys = radiusY / radiusX;
gradient.setAttribute('fx', focusX);
gradient.setAttribute('fy', focusY / ys);
gradient.setAttribute('r', radiusX);
if (ys != 1) gradient.setAttribute('gradientTransform', 'scale(1,' + ys + ')');
gradient.setAttribute('cx', centerX);
gradient.setAttribute('cy', centerY / ys);
return this;
},
fillLinear: function(stops, x1, y1, x2, y2){
var gradient = this._createGradient('fill', 'linearGradient', stops);
if (arguments.length == 5){
gradient.setAttribute('gradientUnits', 'userSpaceOnUse');
} else {
var angle = ((x1 == null) ? 270 : x1) * Math.PI / 180;
var x = Math.cos(angle), y = -Math.sin(angle),
l = (Math.abs(x) + Math.abs(y)) / 2;
x *= l; y *= l;
x1 = 0.5 - x;
x2 = 0.5 + x;
y1 = 0.5 - y;
y2 = 0.5 + y;
}
gradient.setAttribute('x1', x1);
gradient.setAttribute('y1', y1);
gradient.setAttribute('x2', x2);
gradient.setAttribute('y2', y2);
return this;
},
fillImage: function(url, width, height, left, top, color1, color2){
var pattern = this._createBrush('fill', 'pattern');
var image = createElement('image');
image.setAttributeNS(XLINK, 'href', url);
image.setAttribute('width', width);
image.setAttribute('height', height);
image.setAttribute('preserveAspectRatio', 'none'); // none, xMidYMid slice, xMidYMid meet
if (color1 != null){
color1 = new Color(color1);
if (color2 == null){
color2 = new Color(color1);
color2.alpha = 0;
} else {
color2 = new Color(color2);
}
var r = (color1.red - color2.red) / (255 * 3),
g = (color1.green - color2.green) / (255 * 3),
b = (color1.blue - color2.blue) / (255 * 3),
a = (color1.alpha - color2.alpha) / 3;
var matrix = [
r, r, r, 0, color2.red / 255,
g, g, g, 0, color2.green / 255,
b, b, b, 0, color2.blue / 255,
a, a, a, 0, color2.alpha
];
var filter = createElement('filter');
filter.setAttribute('id', 'testfilter' + this.uid);
var cm = createElement('feColorMatrix');
cm.setAttribute('type', 'matrix');
cm.setAttribute('values', matrix.join(' '));
image.setAttribute('fill', '#000');
image.setAttribute('filter', 'url(#testfilter' + this.uid + ')');
filter.appendChild(cm);
pattern.appendChild(filter);
}
pattern.appendChild(image);
pattern.setAttribute('patternUnits', 'userSpaceOnUse');
pattern.setAttribute('patternContentsUnits', 'userSpaceOnUse');
pattern.setAttribute('x', left || 0);
pattern.setAttribute('y', top || 0);
pattern.setAttribute('width', width);
pattern.setAttribute('height', height);
pattern.setAttribute(‘viewBox’, ‘0 0 75 50’); pattern.setAttribute(‘preserveAspectRatio’, ‘xMidYMid slice’);
return this;
},
stroke: function(color, width, cap, join){
var element = this.element;
element.setAttribute('stroke-width', (width != null) ? width : 1);
element.setAttribute('stroke-linecap', (cap != null) ? cap : 'round');
element.setAttribute('stroke-linejoin', (join != null) ? join : 'round');
this._setColor('stroke', color);
return this;
}
});
SVG Shape Class
ART.SVG.Shape = new Class({
Extends: ART.SVG.Base,
initialize: function(path, width, height){
this.parent('path');
this.element.setAttribute('fill-rule', 'evenodd');
this.width = width;
this.height = height;
if (path != null) this.draw(path);
},
draw: function(path, width, height){
if (!(path instanceof ART.Path)) path = new ART.Path(path);
this.element.setAttribute('d', path.toSVG());
if (width != null) this.width = width;
if (height != null) this.height = height;
return this;
}
});
ART.SVG.Image = new Class({
Extends: ART.SVG.Base,
initialize: function(src, width, height){
this.parent('image');
if (arguments.length == 3) this.draw.apply(this, arguments);
},
draw: function(src, width, height){
var element = this.element;
element.setAttributeNS(XLINK, 'href', src);
element.setAttribute('width', width);
element.setAttribute('height', height);
this.width = width;
this.height = height;
return this;
}
});
var fontAnchors = { left: 'start', center: 'middle', right: 'end' },
fontAnchorOffsets = { middle: '50%', end: '100%' };
split each continuous line into individual paths
var splitPaths, splitPath;
function splitMove(sx, sy, x, y){
if (splitPath.length > 3) splitPaths.push(splitPath);
splitPath = ['M', x, y];
};
function splitLine(sx, sy, x, y){
splitPath.push('L', x, y);
};
function splitCurve(sx, sy, p1x, p1y, p2x, p2y, x, y){
splitPath.push('C', p1x, p1y, p2x, p2y, x, y);
};
ART.SVG.Text = new Class({
Extends: ART.SVG.Base,
initialize: function(text, font, alignment, path){
this.parent('text');
this.draw.apply(this, arguments);
},
draw: function(text, font, alignment, path){
var element = this.element;
if (font){
if (typeof font == 'string'){
element.style.font = font;
} else {
for (var key in font){
var ckey = key.camelCase ? key.camelCase() : key;
NOT UNIVERSALLY SUPPORTED OPTIONS if (ckey == ‘kerning’) element.setAttribute(‘kerning’, font[key] ? ‘auto’ : ‘0’); else if (ckey == ‘letterSpacing’) element.setAttribute(‘letter-spacing’, Number(font[key]) + ‘ex’); else if (ckey == ‘rotateGlyphs’) element.setAttribute(‘glyph-orientation-horizontal’, font[key] ? ‘270deg’ : ‘’); else
element.style[ckey] = font[key];
}
element.style.lineHeight = '0.5em';
}
}
if (alignment) element.setAttribute('text-anchor', this.textAnchor = (fontAnchors[alignment] || alignment));
if (path && typeof path != 'number'){
this._createPaths(new ART.Path(path));
} else if (path === false){
this._ejectPaths();
this.pathElements = null;
}
var paths = this.pathElements, child;
while ((child = element.firstChild)){
element.removeChild(child);
}
Note: Gecko will (incorrectly) align gradients for each row, while others applies one for the entire element
var lines = String(text).split(/\r?\n/), l = lines.length,
baseline = 'central';
if (paths && l > paths.length) l = paths.length;
if (hasBaseline) element.setAttribute('dominant-baseline', baseline);
element.setAttributeNS(XML, 'space', 'preserve');
for (var i = 0; i < l; i++){
var line = lines[i], row, content;
if (paths){
row = createElement('textPath');
row.setAttributeNS(XLINK, 'href', '#' + paths[i].getAttribute('id'));
row.setAttribute('startOffset', fontAnchorOffsets[this.textAnchor] || 0);
} else {
row = createElement('tspan');
row.setAttribute('x', 0);
row.setAttribute('y', (i * 1.1 + 0.5) + 'em');
}
if (hasBaseline){
row.setAttribute('dominant-baseline', baseline);
content = row;
} else if (paths){
content = createElement('tspan');
content.setAttribute('dy', '0.35em');
row.appendChild(content);
} else {
content = row;
row.setAttribute('y', (i * 1.1 + 0.85) + 'em');
}
content.setAttributeNS(XML, 'space', 'preserve');
content.appendChild(document.createTextNode(line));
element.appendChild(row);
}
Measure TODO: Move to lazy ES5 left/top/width/height/bottom/right property getters
var bb;
try { bb = element.getBBox(); } catch (x){ }
if (!bb || !bb.width) bb = this._whileInDocument(element.getBBox, element);
this.left = bb.x;
this.top = bb.y;
this.width = bb.width;
this.height = bb.height;
this.right = bb.x + bb.width;
this.bottom = bb.y + bb.height;
return this;
},
TODO: Unify path injection with gradients and imagefills
inject: function(container){
this.parent(container);
this._injectPaths();
return this;
},
eject: function(){
if (this.container){
this._ejectPaths();
this.parent();
this.container = null;
}
return this;
},
_injectPaths: function(){
var paths = this.pathElements;
if (!this.container || !paths) return;
var defs = this.container.defs;
for (var i = 0, l = paths.length; i < l; i++)
defs.appendChild(paths[i]);
},
_ejectPaths: function(){
var paths = this.pathElements;
if (!this.container || !paths) return;
var defs = this.container.defs;
for (var i = 0, l = paths; i < l; i++)
defs.removeChild(paths[i]);
},
_createPaths: function(path){
this._ejectPaths();
var id = 'p' + String.uniqueID() + '-';
splitPaths = []; splitPath = ['M', 0, 0];
path.visit(splitLine, splitCurve, null, splitMove);
splitPaths.push(splitPath);
var result = [];
for (var i = 0, l = splitPaths.length; i < l; i++){
var p = createElement('path');
p.setAttribute('d', splitPaths[i].join(' '));
p.setAttribute('id', id + i);
result.push(p);
}
this.pathElements = result;
this._injectPaths();
},
_whileInDocument: function(fn, bind){
Temporarily inject into the document
var element = this.element,
container = this.container,
parent = element.parentNode,
sibling = element.nextSibling,
body = element.ownerDocument.body,
canvas = new ART.SVG(1, 1).inject(body);
this.inject(canvas);
var result = fn.call(bind);
canvas.eject();
if (container) this.inject(container);
if (parent) parent.insertBefore(element, sibling);
return result;
}
});
})();