Fabric.js 的文本框不换行 [英] Textbox of Fabric.js does not wrap a long word

查看:127
本文介绍了Fabric.js 的文本框不换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Fabric.jsTextbox.我给了一个固定的宽度.但是,如果用户键入一个没有任何空格的长单词,超过了给定的文本框宽度,则它不会换行.

I am using the Textbox of Fabric.js. I have given a fixed width. But if a user types a long word without any space that exceeds the given width of textbox, it does not wrap.

有什么办法吗?

推荐答案

是的,有一个你可能喜欢或不喜欢的解决方案来实现分词:

Yes there is a solution that you may like or not to implement word breaking:

覆盖fabric默认的换行函数:

override the fabric default function for line breaking:

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;
};

用法:

var breakingTextbox = new fabric.Textbox(longText, {
        width: 200,
        breakWords: true
});

这篇关于Fabric.js 的文本框不换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆