IE fix for gradient parsing.

This commit is contained in:
kangax 2012-06-07 12:11:23 +02:00
parent 1bfa25acf4
commit 7791e9c2e0

View file

@ -1,28 +1,32 @@
(function() {
function getColorStopFromStyle(el) {
var style = el.getAttribute('style');
if (style) {
var keyValuePairs = style.split(/\s*;\s*/);
if (keyValuePairs[keyValuePairs.length-1] === '') {
keyValuePairs.pop();
}
for (var i = keyValuePairs.length; i--; ) {
var split = keyValuePairs[i].split(/\s*:\s*/),
key = split[0].trim(),
value = split[1].trim();
if (key === 'stop-color') {
return value;
}
}
}
}
/** @namespace */
fabric.Gradient = {
/**
* @method create
* @static
@ -35,23 +39,23 @@
x2 = options.x2 || ctx.canvas.width,
y2 = options.y2 || 0,
colorStops = options.colorStops;
var gradient = ctx.createLinearGradient(x1, y1, x2, y2);
for (var position in colorStops) {
var colorValue = colorStops[position];
gradient.addColorStop(parseFloat(position), colorValue);
}
return gradient;
},
/**
* @method fromElement
* @static
* @see http://www.w3.org/TR/SVG/pservers.html#LinearGradientElement
*/
fromElement: function(el, ctx, instance) {
/**
* @example:
*
@ -80,18 +84,18 @@
x2: el.getAttribute('x2') || '100%',
y2: el.getAttribute('y2') || 0
};
for (var i = colorStopEls.length; i--; ) {
el = colorStopEls[i];
offset = el.getAttribute('offset');
// convert percents to absolute values
offset = parseFloat(offset) / (/%$/.test(offset) ? 100 : 1);
colorStops[offset] = getColorStopFromStyle(el) || el.getAttribute('stop-color');
}
_convertPercentUnitsToValues(instance, coords);
return fabric.Gradient.create(ctx, {
x1: coords.x1,
y1: coords.y1,
@ -100,17 +104,17 @@
colorStops: colorStops
});
},
/**
* @method forObject
* @static
*/
forObject: function(obj, ctx, options) {
options || (options = { });
_convertPercentUnitsToValues(obj, options);
var gradient = fabric.Gradient.create(ctx, {
var gradient = fabric.Gradient.create(ctx, {
x1: options.x1,
y1: options.y1,
x2: options.x2,
@ -121,7 +125,7 @@
return gradient;
}
};
function _convertPercentUnitsToValues(object, options) {
for (var prop in options) {
if (typeof options[prop] === 'string' && /^\d+%$/.test(options[prop])) {
@ -142,7 +146,7 @@
}
}
}
/**
* Parses an SVG document, returning all of the gradient declarations found in it
* @static
@ -157,20 +161,20 @@
radialGradientEls = doc.getElementsByTagName('radialGradient'),
el,
gradientDefs = { };
for (var i = linearGradientEls.length; i--; ) {
el = linearGradientEls[i];
gradientDefs[el.id] = el;
}
for (var i = radialGradientEls.length; i--; ) {
el = radialGradientEls[i];
gradientDefs[el.id] = el;
}
return gradientDefs;
}
fabric.getGradientDefs = getGradientDefs;
})();