Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix gradient toSVG for radial gradients #3807

Merged
merged 3 commits into from
Mar 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/elements_parser.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
fabric.ElementsParser = function(elements, callback, options, reviver) {
fabric.ElementsParser = function(elements, callback, options, reviver, parsingOptions) {
this.elements = elements;
this.callback = callback;
this.options = options;
this.reviver = reviver;
this.svgUid = (options && options.svgUid) || 0;
this.parsingOptions = parsingOptions;
};

fabric.ElementsParser.prototype.parse = function() {
Expand Down
49 changes: 35 additions & 14 deletions src/gradient.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@
for (var position in colorStops) {
var color = new fabric.Color(colorStops[position]);
this.colorStops.push({
offset: position,
offset: parseFloat(position),
color: color.toRgb(),
opacity: color.getAlpha()
});
Expand Down Expand Up @@ -170,16 +170,16 @@
*/
toSVG: function(object) {
var coords = fabric.util.object.clone(this.coords),
markup, commonAttributes;

markup, commonAttributes, colorStops = this.colorStops,
needsSwap = coords.r1 > coords.r2;
// colorStops must be sorted ascending
this.colorStops.sort(function(a, b) {
return a.offset - b.offset;
});

if (!(object.group && object.group.type === 'path-group')) {
for (var prop in coords) {
if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
if (prop === 'x1' || prop === 'x2') {
coords[prop] += this.offsetX - object.width / 2;
}
else if (prop === 'y1' || prop === 'y2') {
Expand All @@ -205,24 +205,45 @@
];
}
else if (this.type === 'radial') {
// svg radial gradient has just 1 radius. the biggest.
markup = [
'<radialGradient ',
commonAttributes,
' cx="', coords.x2,
'" cy="', coords.y2,
'" r="', coords.r2,
'" fx="', coords.x1,
'" fy="', coords.y1,
' cx="', needsSwap ? coords.x1 : coords.x2,
'" cy="', needsSwap ? coords.y1 : coords.y2,
'" r="', needsSwap ? coords.r1 : coords.r2,
'" fx="', needsSwap ? coords.x2 : coords.x1,
'" fy="', needsSwap ? coords.y2 : coords.y1,
'">\n'
];
}

for (var i = 0; i < this.colorStops.length; i++) {
if (this.type === 'radial') {
if (needsSwap) {
// svg goes from internal to external radius. if radius are inverted, swap color stops.
colorStops = colorStops.concat().reverse();
for (var i = 0; i < colorStops.length; i++) {
colorStops[i].offset = 1 - colorStops[i].offset;
}
}
var minRadius = Math.min(coords.r1, coords.r2);
if (minRadius > 0) {
// i have to shift all colorStops and add new one in 0.
var maxRadius = Math.max(coords.r1, coords.r2),
percentageShift = minRadius / maxRadius;
for (var i = 0; i < colorStops.length; i++) {
colorStops[i].offset += percentageShift * (1 - colorStops[i].offset);
}
}
}

for (var i = 0; i < colorStops.length; i++) {
var colorStop = colorStops[i];
markup.push(
'<stop ',
'offset="', (this.colorStops[i].offset * 100) + '%',
'" style="stop-color:', this.colorStops[i].color,
(this.colorStops[i].opacity !== null ? ';stop-opacity: ' + this.colorStops[i].opacity : ';'),
'offset="', (colorStop.offset * 100) + '%',
'" style="stop-color:', colorStop.color,
(colorStop.opacity !== null ? ';stop-opacity: ' + colorStop.opacity : ';'),
'"/>\n'
);
}
Expand Down Expand Up @@ -274,7 +295,7 @@
if (typeof opacity !== 'undefined') {
color = new fabric.Color(color).setAlpha(opacity).toRgba();
}
gradient.addColorStop(parseFloat(offset), color);
gradient.addColorStop(offset, color);
}

return gradient;
Expand Down
32 changes: 19 additions & 13 deletions src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -602,8 +602,10 @@
* @param {Function} callback Callback to call when parsing is finished;
* It's being passed an array of elements (parsed from a document).
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
* @param {Object} [parsingOptions] options for parsing document
* @param {String} [parsingOptions.crossOrigin] crossOrigin settings
*/
fabric.parseSVGDocument = function(doc, callback, reviver) {
fabric.parseSVGDocument = function(doc, callback, reviver, parsingOptions) {
if (!doc) {
return;
}
Expand All @@ -613,7 +615,7 @@
var svgUid = fabric.Object.__uid++,
options = applyViewboxTransform(doc),
descendants = fabric.util.toArray(doc.getElementsByTagName('*'));

options.crossOrigin = parsingOptions && parsingOptions.crossOrigin;
options.svgUid = svgUid;

if (descendants.length === 0 && fabric.isLikelyNode) {
Expand Down Expand Up @@ -645,7 +647,7 @@
if (callback) {
callback(instances, options);
}
}, clone(options), reviver);
}, clone(options), reviver, parsingOptions);
};

var reFontDeclaration = new RegExp(
Expand Down Expand Up @@ -797,8 +799,8 @@
* @param {Object} [options] Options object
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
parseElements: function(elements, callback, options, reviver) {
new fabric.ElementsParser(elements, callback, options, reviver).parse();
parseElements: function(elements, callback, options, reviver, parsingOptions) {
new fabric.ElementsParser(elements, callback, options, reviver, parsingOptions).parse();
},

/**
Expand Down Expand Up @@ -924,8 +926,10 @@
* @param {String} url
* @param {Function} callback
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
* @param {Object} [options] Object containing options for parsing
* @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources
*/
loadSVGFromURL: function(url, callback, reviver) {
loadSVGFromURL: function(url, callback, reviver, options) {

url = url.replace(/^\n\s*/, '').trim();
new fabric.util.request(url, {
Expand All @@ -946,9 +950,9 @@
callback && callback(null);
}

fabric.parseSVGDocument(xml.documentElement, function (results, options) {
callback && callback(results, options);
}, reviver);
fabric.parseSVGDocument(xml.documentElement, function (results, _options) {
callback && callback(results, _options);
}, reviver, options);
}
},

Expand All @@ -958,8 +962,10 @@
* @param {String} string
* @param {Function} callback
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
* @param {Object} [options] Object containing options for parsing
* @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources
*/
loadSVGFromString: function(string, callback, reviver) {
loadSVGFromString: function(string, callback, reviver, options) {
string = string.trim();
var doc;
if (typeof DOMParser !== 'undefined') {
Expand All @@ -975,9 +981,9 @@
doc.loadXML(string.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i, ''));
}

fabric.parseSVGDocument(doc.documentElement, function (results, options) {
callback(results, options);
}, reviver);
fabric.parseSVGDocument(doc.documentElement, function (results, _options) {
callback(results, _options);
}, reviver, options);
}
});

Expand Down
2 changes: 1 addition & 1 deletion src/shapes/image.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@
* @see {@link http://www.w3.org/TR/SVG/struct.html#ImageElement}
*/
fabric.Image.ATTRIBUTE_NAMES =
fabric.SHARED_ATTRIBUTES.concat('x y width height preserveAspectRatio xlink:href'.split(' '));
fabric.SHARED_ATTRIBUTES.concat('x y width height preserveAspectRatio xlink:href crossOrigin'.split(' '));

/**
* Returns {@link fabric.Image} instance from an SVG element
Expand Down
70 changes: 68 additions & 2 deletions test/unit/gradient.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,47 @@
});
}

function createRadialGradientWithInternalRadius() {
return new fabric.Gradient({
type: 'radial',
coords: {
x1: 0,
y1: 10,
x2: 100,
y2: 200,
r1: 10,
r2: 50
},
colorStops: [
{ offset: 0, color: 'red' },
{ offset: 1, color: 'green', opacity: 0 }
]
});
}

function createRadialGradientSwapped() {
return new fabric.Gradient({
type: 'radial',
coords: {
x1: 0,
y1: 10,
x2: 100,
y2: 200,
r1: 50,
r2: 10
},
colorStops: [
{ offset: 0, color: 'red' },
{ offset: 1, color: 'green', opacity: 0 }
]
});
}

var SVG_LINEAR = '<linearGradient id="SVGID_0" gradientUnits="userSpaceOnUse" x1="-50" y1="-40" x2="50" y2="150">\n<stop offset="0%" style="stop-color:red;stop-opacity: 0"/>\n<stop offset="100%" style="stop-color:green;stop-opacity: undefined"/>\n</linearGradient>\n';
var SVG_RADIAL = '<radialGradient id="SVGID_0" gradientUnits="userSpaceOnUse" cx="50" cy="150" r="50" fx="-50" fy="-40">\n<stop offset="0%" style="stop-color:red;stop-opacity: undefined"/>\n<stop offset="100%" style="stop-color:green;stop-opacity: 0"/>\n</radialGradient>\n';
var SVG_INTERNALRADIUS = '<radialGradient id="SVGID_0" gradientUnits="userSpaceOnUse" cx="50" cy="150" r="50" fx="-50" fy="-40">\n<stop offset="20%" style="stop-color:red;stop-opacity: undefined"/>\n<stop offset="100%" style="stop-color:green;stop-opacity: 0"/>\n</radialGradient>\n';
var SVG_SWAPPED = '<radialGradient id="SVGID_0" gradientUnits="userSpaceOnUse" cx="-50" cy="-40" r="50" fx="50" fy="150">\n<stop offset="20%" style="stop-color:green;stop-opacity: 0"/>\n<stop offset="100%" style="stop-color:red;stop-opacity: undefined"/>\n</radialGradient>\n';

test('constructor linearGradient', function() {
ok(fabric.Gradient);

Expand Down Expand Up @@ -634,10 +675,35 @@

test('toSVG', function() {
var gradient = createLinearGradient();

ok(typeof gradient.toSVG == 'function');
});

test('toSVG linear', function() {
fabric.Object.__uid = 0;
var gradient = createLinearGradient();
var obj = new fabric.Object({ width: 100, height: 100 });
equal(gradient.toSVG(obj), SVG_LINEAR);
});

test('toSVG radial', function() {
fabric.Object.__uid = 0;
var gradient = createRadialGradient();
var obj = new fabric.Object({ width: 100, height: 100 });
equal(gradient.toSVG(obj), SVG_RADIAL);
});

test('toSVG radial with r1 > 0', function() {
fabric.Object.__uid = 0;
var gradient = createRadialGradientWithInternalRadius();
var obj = new fabric.Object({ width: 100, height: 100 });
equal(gradient.toSVG(obj), SVG_INTERNALRADIUS);
});

// TODO: test toSVG
test('toSVG radial with r1 > 0', function() {
fabric.Object.__uid = 0;
var gradient = createRadialGradientSwapped();
var obj = new fabric.Object({ width: 100, height: 100 });
equal(gradient.toSVG(obj), SVG_SWAPPED);
});

})();