diff --git a/src/shapes/path.class.js b/src/shapes/path.class.js index ab379e5b3cf..bf85b12bafd 100644 --- a/src/shapes/path.class.js +++ b/src/shapes/path.class.js @@ -6,6 +6,7 @@ min = fabric.util.array.min, max = fabric.util.array.max, extend = fabric.util.object.extend, + clone = fabric.util.object.clone, _toString = Object.prototype.toString, toFixed = fabric.util.toFixed; @@ -47,13 +48,19 @@ * @param {Object} [options] Options object * @return {fabric.Path} thisArg */ - initialize: function(path, options) { - options = options || { }; + initialize: function (path, options) { + options = clone(options || {}); + delete options.path; this.callSuper('initialize', options); - if (!path) { - path = []; - } + this._setPath(path || [], options); + }, + /** + * @private + * @param {Array|String} path Path data (sequence of coordinates and corresponding "command" tokens) + * @param {Object} [options] Options object + */ + _setPath: function (path, options) { var fromArray = _toString.call(path) === '[object Array]'; this.path = fromArray @@ -63,10 +70,7 @@ fabric.util.parsePath(path) ); - if (!this.path) { - return; - } - fabric.Polyline.prototype._setPositionDimensions.call(this, options); + fabric.Polyline.prototype._setPositionDimensions.call(this, options || {}); }, /** diff --git a/test/unit/path.js b/test/unit/path.js index 8b8966260cd..dbc1a143a76 100644 --- a/test/unit/path.js +++ b/test/unit/path.js @@ -56,6 +56,12 @@ getPathObject('M 100 100 L 300 100 L 200 300 z', callback); } + function updatePath(pathObject, value, preservePosition) { + const { left, top } = pathObject; + pathObject._setPath(value); + preservePosition && pathObject.set({ left, top }); + } + QUnit.module('fabric.Path', { beforeEach: function() { fabric.Object.__uid = 0; @@ -115,6 +121,27 @@ done(); }); + QUnit.test('set path after initialization', function (assert) { + var done = assert.async(); + var path = new fabric.Path('M 100 100 L 200 100 L 170 200 z', REFERENCE_PATH_OBJECT); + updatePath(path, REFERENCE_PATH_OBJECT.path, true); + assert.deepEqual(path.toObject(), REFERENCE_PATH_OBJECT); + updatePath(path, REFERENCE_PATH_OBJECT.path, false); + var left = path.left; + var top = path.top; + path.center(); + assert.equal(left, path.left); + assert.equal(top, path.top); + var opts = fabric.util.object.clone(REFERENCE_PATH_OBJECT); + delete opts.path; + path.set(opts); + updatePath(path, 'M 100 100 L 300 100 L 200 300 z', true); + makePathObject(function (cleanPath) { + assert.deepEqual(path.toObject(), cleanPath.toObject()); + done(); + }); + }); + QUnit.test('toString', function(assert) { var done = assert.async(); makePathObject(function(path) {