Reputation: 4530
I have a piece of code that creates a new Textbox
this way:
new fabric.Textbox('Ajouter du texte')
The problem is the text box is to small compare to its content:
If I set a fixed width, I get some padding around:
new fabric.Textbox('Ajouter du texte', {width: 350})
How can I adjust the text box size to match the text selection size? I can't find anything about how to get the selection dimensions.
I'm using fabric version 4.0.0-beta.5
.
Upvotes: 3
Views: 3863
Reputation: 4530
The solution I keep for now is to increase the width gradually till I get no more than 1 line:
const text = new fabric.Textbox("Ajouter du texte")
while (text.textLines.length > 1) {
text.set({width: text.getScaledWidth() + 1})
}
Feel free to propose a better solution, so I can update the accepted answer.
[EDIT]
To make it work during text edition:
function adjustTextWidth(evt: fabric.IEvent) {
if (evt.target instanceof fabric.IText) {
const text = evt.target.text || ""
while (evt.target.textLines.length > text.split("\n").length) {
evt.target.set({width: evt.target.getScaledWidth() + 1})
}
}
}
canvas.on("text:changed", adjustTextWidth)
[EDIT2]
I found a better way to achieve my goal:
fabric.Textbox.prototype._wordJoiners = /[]/;
This way, the space is not considered a word joiner and the text breaks only when the user types Enter
. I also added this function to adjust the textbox width when text is removed:
function fitTextboxToContent(text: fabric.IText) {
const textLinesMaxWidth = text.textLines.reduce((max, _, i) => Math.max(max, text.getLineWidth(i)), 0);
text.set({width: textLinesMaxWidth});
}
Upvotes: 7
Reputation: 1088
I've searched in the TextBox documentation, but haven't found anything that automatically adjusts the container to the text size.
The best thing you can do is to get the size of each line and if the width sum is smaller than a maximum wanted value, then set the width to the Text Box. For some reason, you need to add also a small width to it.
var canvas = new fabric.Canvas("canvas");
var text = new fabric.Textbox("Ajouter du texte");
var textSize = 0;
for (var i = 0; i < text._textLines.length; i++) {
textSize += text.measureLine(i).width;
}
var augmentedTextSize = textSize + 25;
if (augmentedTextSize < 500) {
text.set({ width: augmentedTextSize });
}
canvas.add(text);
canvas.renderAll();
Check this example: https://codesandbox.io/s/stackoverflow-60411035-fabric-js-400-beta5-7s7id
It would be nice to have some kind of property on the TextBox like for example "max_width", that if the text is smaller than that, then automatically adjust the size to the text size.
Upvotes: 0