From 1763f14e22c4637516209a98f40cf4e4ac876879 Mon Sep 17 00:00:00 2001 From: Andrea Bogazzi Date: Sun, 18 Feb 2018 23:50:08 +0100 Subject: [PATCH] added image crop ToSVG support (#4738) * added svg crop support --- src/shapes/image.class.js | 28 +++++++++++++++++++++++----- test/unit/image.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/shapes/image.class.js b/src/shapes/image.class.js index 089db6a07d3..512fdd710bb 100644 --- a/src/shapes/image.class.js +++ b/src/shapes/image.class.js @@ -280,6 +280,14 @@ return object; }, + /** + * Returns true if an image has crop applied, inspecting values of cropX,cropY,width,hight. + * @return {Boolean} + */ + hasCrop: function() { + return this.cropX || this.cropY || this.width < this._element.width || this.height < this._element.height; + }, + /* _TO_SVG_START_ */ /** * Returns SVG representation of an instance @@ -287,17 +295,27 @@ * @return {String} svg representation of an instance */ toSVG: function(reviver) { - var markup = this._createBaseSVGMarkup(), x = -this.width / 2, y = -this.height / 2; + var markup = this._createBaseSVGMarkup(), x = -this.width / 2, y = -this.height / 2, clipPath = ''; + if (this.hasCrop()) { + var clipPathId = fabric.Object.__uid++; + markup.push( + '\n', + '\t\n', + '\n' + ); + clipPath = ' clip-path="url(#imageCrop_' + clipPathId + ')" '; + } markup.push('\n'); var imageMarkup = ['\t\n']; + '" width="', this._element.width || this._element.naturalWidth, + '" height="', this._element.height || this._element.height, + '"', clipPath, + '>\n']; if (this.paintFirst === 'fill') { Array.prototype.push.apply(markup, imageMarkup); } diff --git a/test/unit/image.js b/test/unit/image.js index c7e05c6e5ea..b886b296379 100644 --- a/test/unit/image.js +++ b/test/unit/image.js @@ -208,6 +208,39 @@ }); }); + QUnit.test('toSVG wit crop', function(assert) { + var done = assert.async(); + createImageObject(function(image) { + image.cropX = 1; + image.cropY = 1; + image.width -= 2; + image.height -= 2; + fabric.Object.__uid = 1; + var expectedSVG = '\n\t\n\n\n\t\n\n'; + assert.equal(image.toSVG(), expectedSVG); + done(); + }); + }); + + QUnit.test('hasCrop', function(assert) { + var done = assert.async(); + createImageObject(function(image) { + assert.ok(typeof image.hasCrop === 'function'); + assert.equal(image.hasCrop(), false, 'standard image has no crop'); + image.cropX = 1; + assert.equal(image.hasCrop(), true, 'cropX !== 0 gives crop true'); + image.cropX = 0; + image.cropY = 1; + assert.equal(image.hasCrop(), true, 'cropY !== 0 gives crop true'); + image.width -= 1; + assert.equal(image.hasCrop(), true, 'width < element.width gives crop true'); + image.width += 1; + image.height -= 1; + assert.equal(image.hasCrop(), true, 'height < element.height gives crop true'); + done(); + }); + }); + QUnit.test('toSVG', function(assert) { var done = assert.async(); createImageObject(function(image) {