Skip to content

Commit

Permalink
Fix/text object position bug (#405) (fix #401)
Browse files Browse the repository at this point in the history
* fix: rotated text object position bug

* fix: added test for text position bug

* apply codereview for adjust text origin position

Co-authored-by: jwc <[email protected]>
  • Loading branch information
jinwoo-kim-nhn and jwc committed Jun 10, 2020
1 parent 2ce8814 commit 20601cf
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 12 deletions.
35 changes: 23 additions & 12 deletions src/js/component/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,7 @@ class Text extends Component {
if (this.useItext) {
canvas.forEachObject(obj => {
if (obj.type === 'i-text') {
obj.set({
left: obj.left - (obj.width / 2),
top: obj.top - (obj.height / 2),
originX: 'left',
originY: 'top'
});
this.adjustOriginPosition(obj, 'start');
}
});
} else {
Expand All @@ -172,12 +167,7 @@ class Text extends Component {
if (obj.text === '') {
canvas.remove(obj);
} else {
obj.set({
left: obj.left + (obj.width / 2),
top: obj.top + (obj.height / 2),
originX: 'center',
originY: 'center'
});
this.adjustOriginPosition(obj, 'end');
}
}
});
Expand All @@ -195,6 +185,27 @@ class Text extends Component {
});
}

/**
* Adjust the origin position
* @param {fabric.Object} text - text object
* @param {string} editStatus - 'start' or 'end'
*/
adjustOriginPosition(text, editStatus) {
let [originX, originY] = ['center', 'center'];
if (editStatus === 'start') {
[originX, originY] = ['left', 'top'];
}

const {x: left, y: top} = text.getPointByOrigin(originX, originY);
text.set({
left,
top,
originX,
originY
});
text.setCoords();
}

/**
* Add new text on canvas image
* @param {string} text - Initial input text
Expand Down
22 changes: 22 additions & 0 deletions test/text.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,28 @@ describe('Text', () => {
});
});

it('Rotated text elements must also maintain consistent left and top positions after entering and exiting drawing mode.', () => {
const left = 10;
const top = 20;
const newText = new fabric.IText('testString', {
left,
top,
width: 30,
height: 50,
angle: 40,
originX: 'center',
originY: 'center'
});
text.useItext = true;
canvas.add(newText);

text.start();
text.end();

expect(newText.left).toEqual(left);
expect(newText.top).toEqual(top);
});

it('change() should change contents in the text object as input.', () => {
text.add('text123', {});

Expand Down

0 comments on commit 20601cf

Please sign in to comment.