Abh*_*nav 6 javascript canvas html5-canvas fabricjs
我使用Textbox的Fabric.js.我给了一个固定的宽度.但是,如果用户键入一个长字而没有任何超出给定文本框宽度的空格,则它不会换行.
有解决方案吗
是的,您可能想要或不想实施解决方案的解决方案:
覆盖换行的结构默认功能:
fabric.Textbox.prototype._wrapLine = function(ctx, text, lineIndex) {
var lineWidth = 0,
lines = [],
line = '',
words = text.split(' '),
word = '',
letter = '',
offset = 0,
infix = ' ',
wordWidth = 0,
infixWidth = 0,
letterWidth = 0,
largestWordWidth = 0;
for (var i = 0; i < words.length; i++) {
word = words[i];
wordWidth = this._measureText(ctx, word, lineIndex, offset);
lineWidth += infixWidth;
// Break Words if wordWidth is greater than textbox width
if (this.breakWords && wordWidth > this.width) {
line += infix;
var wordLetters = word.split('');
while (wordLetters.length) {
letterWidth = this._getWidthOfChar(ctx, wordLetters[0], lineIndex, offset);
if (lineWidth + letterWidth > this.width) {
lines.push(line);
line = '';
lineWidth = 0;
}
line += wordLetters.shift();
offset++;
lineWidth += letterWidth;
}
word = '';
} else {
lineWidth += wordWidth;
}
if (lineWidth >= this.width && line !== '') {
lines.push(line);
line = '';
lineWidth = wordWidth;
}
if (line !== '' || i === 1) {
line += infix;
}
line += word;
offset += word.length;
infixWidth = this._measureText(ctx, infix, lineIndex, offset);
offset++;
// keep track of largest word
if (wordWidth > largestWordWidth && !this.breakWords) {
largestWordWidth = wordWidth;
}
}
i && lines.push(line);
if (largestWordWidth > this.dynamicMinWidth) {
this.dynamicMinWidth = largestWordWidth;
}
return lines;
};
Run Code Online (Sandbox Code Playgroud)
用法:
var breakingTextbox = new fabric.Textbox(longText, {
width: 200,
breakWords: true
});
Run Code Online (Sandbox Code Playgroud)
对于 Fabric.js 3.0.0+,您可以使用splitByGrapheme属性。
在文本框上,将其设置为 true:
const letterBreakingTextBox = new fabric.Textbox(yourLongText, {
width: 200,
textAlign: 'left', // you can use specify the text align
splitByGrapheme: true
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3646 次 |
| 最近记录: |