fabric.js/src/parser.js

424 lines
13 KiB
JavaScript
Raw Normal View History

(function(global) {
"use strict";
2010-06-09 22:34:55 +00:00
2010-10-19 20:27:24 +00:00
/**
* @name fabric
* @namespace
*/
var fabric = global.fabric || (global.fabric = { }),
extend = fabric.util.object.extend,
capitalize = fabric.util.string.capitalize,
clone = fabric.util.object.clone;
2010-06-09 22:34:55 +00:00
var attributesMap = {
'cx': 'left',
'x': 'left',
'cy': 'top',
'y': 'top',
'r': 'radius',
'fill-opacity': 'opacity',
'fill-rule': 'fillRule',
'stroke-width': 'strokeWidth',
'transform': 'transformMatrix'
};
/**
* Returns an object of attributes' name/value, given element and an array of attribute names;
* Parses parent "g" nodes recursively upwards.
* @static
* @memberOf fabric
* @method parseAttributes
2010-06-09 22:34:55 +00:00
* @param {DOMElement} element Element to parse
* @param {Array} attributes Array of attributes to parse
* @return {Object} object containing parsed attributes' names/values
*/
function parseAttributes(element, attributes) {
if (!element) {
return;
}
2010-06-09 22:34:55 +00:00
var value,
parsed,
parentAttributes = { };
// if there's a parent container (`g` node), parse its attributes recursively upwards
if (element.parentNode && /^g$/i.test(element.parentNode.nodeName)) {
parentAttributes = fabric.parseAttributes(element.parentNode, attributes);
2010-06-09 22:34:55 +00:00
}
var ownAttributes = attributes.reduce(function(memo, attr) {
2010-06-09 22:34:55 +00:00
value = element.getAttribute(attr);
parsed = parseFloat(value);
if (value) {
// "normalize" attribute values
if ((attr === 'fill' || attr === 'stroke') && value === 'none') {
value = '';
}
if (attr === 'fill-rule') {
value = (value === 'evenodd') ? 'destination-over' : value;
}
if (attr === 'transform') {
value = fabric.parseTransformAttribute(value);
2010-06-09 22:34:55 +00:00
}
// transform attribute names
if (attr in attributesMap) {
attr = attributesMap[attr];
}
memo[attr] = isNaN(parsed) ? value : parsed;
}
return memo;
}, { });
2010-06-09 22:34:55 +00:00
// add values parsed from style, which take precedence over attributes
// (see: http://www.w3.org/TR/SVG/styling.html#UsingPresentationAttributes)
ownAttributes = extend(ownAttributes, fabric.parseStyleAttribute(element));
return extend(parentAttributes, ownAttributes);
2010-06-09 22:34:55 +00:00
};
/**
2010-10-19 20:27:24 +00:00
* Parses "transform" attribute, returning an array of values
2010-06-09 22:34:55 +00:00
* @static
* @function
* @memberOf fabric
* @method parseTransformAttribute
2010-06-09 22:34:55 +00:00
* @param attributeValue {String} string containing attribute value
* @return {Array} array of 6 elements representing transformation matrix
*/
fabric.parseTransformAttribute = (function() {
2010-06-09 22:34:55 +00:00
function rotateMatrix(matrix, args) {
var angle = args[0];
matrix[0] = Math.cos(angle);
matrix[1] = Math.sin(angle);
matrix[2] = -Math.sin(angle);
matrix[3] = Math.cos(angle);
}
function scaleMatrix(matrix, args) {
var multiplierX = args[0],
multiplierY = (args.length === 2) ? args[1] : args[0];
matrix[0] = multiplierX;
matrix[3] = multiplierY;
}
function skewXMatrix(matrix, args) {
matrix[2] = args[0];
}
function skewYMatrix(matrix, args) {
matrix[1] = args[0];
}
function translateMatrix(matrix, args) {
matrix[4] = args[0];
if (args.length === 2) {
matrix[5] = args[1];
}
}
// identity matrix
var iMatrix = [
1, // a
0, // b
0, // c
1, // d
0, // e
0 // f
],
// == begin transform regexp
number = '(?:[-+]?\\d+(?:\\.\\d+)?(?:e[-+]?\\d+)?)',
comma_wsp = '(?:\\s+,?\\s*|,\\s*)',
skewX = '(?:(skewX)\\s*\\(\\s*(' + number + ')\\s*\\))',
skewY = '(?:(skewY)\\s*\\(\\s*(' + number + ')\\s*\\))',
rotate = '(?:(rotate)\\s*\\(\\s*(' + number + ')(?:' + comma_wsp + '(' + number + ')' + comma_wsp + '(' + number + '))?\\s*\\))',
scale = '(?:(scale)\\s*\\(\\s*(' + number + ')(?:' + comma_wsp + '(' + number + '))?\\s*\\))',
translate = '(?:(translate)\\s*\\(\\s*(' + number + ')(?:' + comma_wsp + '(' + number + '))?\\s*\\))',
matrix = '(?:(matrix)\\s*\\(\\s*' +
'(' + number + ')' + comma_wsp +
'(' + number + ')' + comma_wsp +
'(' + number + ')' + comma_wsp +
'(' + number + ')' + comma_wsp +
'(' + number + ')' + comma_wsp +
'(' + number + ')' +
'\\s*\\))',
transform = '(?:' +
matrix + '|' +
translate + '|' +
scale + '|' +
rotate + '|' +
skewX + '|' +
skewY +
')',
transforms = '(?:' + transform + '(?:' + comma_wsp + transform + ')*' + ')',
transform_list = '^\\s*(?:' + transforms + '?)\\s*$',
// http://www.w3.org/TR/SVG/coords.html#TransformAttribute
reTransformList = new RegExp(transform_list),
// == end transform regexp
reTransform = new RegExp(transform);
return function(attributeValue) {
// start with identity matrix
var matrix = iMatrix.concat();
2010-06-09 22:34:55 +00:00
// return if no argument was given or
// an argument does not match transform attribute regexp
if (!attributeValue || (attributeValue && !reTransformList.test(attributeValue))) {
return matrix;
}
attributeValue.replace(reTransform, function(match) {
var m = new RegExp(transform).exec(match).filter(function (match) {
return (match !== '' && match != null);
2010-06-09 22:34:55 +00:00
}),
operation = m[1],
args = m.slice(2).map(parseFloat);
switch(operation) {
case 'translate':
translateMatrix(matrix, args);
break;
case 'rotate':
rotateMatrix(matrix, args);
break;
case 'scale':
scaleMatrix(matrix, args);
break;
case 'skewX':
skewXMatrix(matrix, args);
break;
case 'skewY':
skewYMatrix(matrix, args);
break;
case 'matrix':
matrix = args;
break;
}
})
return matrix;
}
})();
/**
2010-10-19 20:27:24 +00:00
* Parses "points" attribute, returning an array of values
2010-06-09 22:34:55 +00:00
* @static
* @memberOf fabric
* @method parsePointsAttribute
2010-06-09 22:34:55 +00:00
* @param points {String} points attribute string
* @return {Array} array of points
*/
function parsePointsAttribute(points) {
2010-06-09 22:34:55 +00:00
// points attribute is required and must not be empty
if (!points) return null;
points = points.trim();
var asPairs = points.indexOf(',') > -1;
points = points.split(/\s+/);
var parsedPoints = [ ];
// points could look like "10,20 30,40" or "10 20 30 40"
if (asPairs) {
for (var i = 0, len = points.length; i < len; i++) {
var pair = points[i].split(',');
parsedPoints.push({ x: parseFloat(pair[0]), y: parseFloat(pair[1]) });
}
}
else {
for (var i = 0, len = points.length; i < len; i+=2) {
parsedPoints.push({ x: parseFloat(points[i]), y: parseFloat(points[i+1]) });
}
}
2010-06-09 22:34:55 +00:00
// odd number of points is an error
if (parsedPoints.length % 2 !== 0) {
// return null;
2010-06-09 22:34:55 +00:00
}
2010-06-09 22:34:55 +00:00
return parsedPoints;
};
/**
2010-10-19 20:27:24 +00:00
* Parses "style" attribute, retuning an object with values
2010-06-09 22:34:55 +00:00
* @static
* @memberOf fabric
* @method parseStyleAttribute
* @param {SVGElement} element Element to parse
* @return {Object} Objects with values parsed from style attribute of an element
2010-06-09 22:34:55 +00:00
*/
function parseStyleAttribute(element) {
var oStyle = { },
style = element.getAttribute('style');
if (style) {
if (typeof style == 'string') {
style = style.replace(/;$/, '').split(';');
oStyle = style.reduce(function(memo, current) {
2010-06-09 22:34:55 +00:00
var attr = current.split(':'),
key = attr[0].trim(),
value = attr[1].trim();
2010-06-09 22:34:55 +00:00
memo[key] = value;
return memo;
}, { });
2010-06-09 22:34:55 +00:00
}
else {
for (var prop in style) {
if (typeof style[prop] !== 'undefined') {
oStyle[prop] = style[prop];
}
}
}
}
return oStyle;
};
/**
2010-10-19 20:27:24 +00:00
* Transforms an array of svg elements to corresponding fabric.* instances
2010-06-09 22:34:55 +00:00
* @static
* @memberOf fabric
* @method parseElements
* @param {Array} elements Array of elements to parse
* @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements)
* @param {Object} options Options object
2010-06-09 22:34:55 +00:00
*/
function parseElements(elements, callback, options) {
var instances = Array(elements.length), i = elements.length;
function checkIfDone() {
if (--i === 0) {
instances = instances.filter(function(el) {
return el != null;
});
callback(instances);
}
}
elements.map(function(el, index) {
var klass = fabric[capitalize(el.tagName)];
2010-06-09 22:34:55 +00:00
if (klass && klass.fromElement) {
try {
if (klass.fromElement.async) {
klass.fromElement(el, (function(index) {
return function(obj) {
instances.splice(index, 0, obj);
checkIfDone();
};
})(index), options);
}
else {
instances.splice(index, 0, klass.fromElement(el, options));
checkIfDone();
}
2010-06-09 22:34:55 +00:00
}
catch(e) {
fabric.log(e.message || e);
2010-06-09 22:34:55 +00:00
}
}
else {
checkIfDone();
}
2010-06-09 22:34:55 +00:00
});
};
/**
* Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback
2010-06-09 22:34:55 +00:00
* @static
* @function
* @memberOf fabric
* @method parseSVGDocument
* @param {SVGDocument} doc SVG document to parse
* @param {Function} callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document).
2010-06-09 22:34:55 +00:00
*/
fabric.parseSVGDocument = (function() {
2010-06-09 22:34:55 +00:00
var reAllowedSVGTagNames = /^(path|circle|polygon|polyline|ellipse|rect|line|image)$/;
2010-06-09 22:34:55 +00:00
// http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
// \d doesn't quite cut it (as we need to match an actual float number)
// matches, e.g.: +14.56e-12, etc.
var reNum = '(?:[-+]?\\d+(?:\\.\\d+)?(?:e[-+]?\\d+)?)';
var reViewBoxAttrValue = new RegExp(
'^' +
'\\s*(' + reNum + '+)\\s*,?' +
'\\s*(' + reNum + '+)\\s*,?' +
'\\s*(' + reNum + '+)\\s*,?' +
'\\s*(' + reNum + '+)\\s*' +
'$'
);
function hasAncestorWithNodeName(element, nodeName) {
2010-06-09 22:34:55 +00:00
while (element && (element = element.parentNode)) {
if (nodeName.test(element.nodeName)) {
2010-06-09 22:34:55 +00:00
return true;
}
}
return false;
}
return function(doc, callback) {
if (!doc) return;
var descendants = fabric.util.toArray(doc.getElementsByTagName('*'));
2010-06-09 22:34:55 +00:00
var elements = descendants.filter(function(el) {
2010-06-09 22:34:55 +00:00
return reAllowedSVGTagNames.test(el.tagName) &&
!hasAncestorWithNodeName(el, /^(?:pattern|defs)$/); // http://www.w3.org/TR/SVG/struct.html#DefsElement
2010-06-09 22:34:55 +00:00
});
if (!elements || (elements && !elements.length)) return;
var viewBoxAttr = doc.getAttribute('viewBox'),
widthAttr = doc.getAttribute('width'),
heightAttr = doc.getAttribute('height'),
width = null,
height = null,
minX,
minY;
if (viewBoxAttr && (viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue))) {
minX = parseInt(viewBoxAttr[1], 10);
minY = parseInt(viewBoxAttr[2], 10);
width = parseInt(viewBoxAttr[3], 10);
height = parseInt(viewBoxAttr[4], 10);
}
// values of width/height attributes overwrite those extracted from viewbox attribute
width = widthAttr ? parseFloat(widthAttr) : width;
height = heightAttr ? parseFloat(heightAttr) : height;
var options = {
width: width,
height: height
};
fabric.parseElements(elements, function(instances) {
if (callback) {
callback(instances, options);
}
}, clone(options));
2010-06-09 22:34:55 +00:00
};
})();
extend(fabric, {
2010-06-09 22:34:55 +00:00
parseAttributes: parseAttributes,
parseElements: parseElements,
parseStyleAttribute: parseStyleAttribute,
parsePointsAttribute: parsePointsAttribute
});
})(this);