javascript - Fabric.js 的文本框不换长字

标签 javascript canvas html5-canvas fabricjs

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

有什么解决办法吗?

最佳答案

是的,您可能喜欢或不喜欢实现分词的解决方案:

覆盖 fabric 默认的换行函数:

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

关于javascript - Fabric.js 的文本框不换长字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37858237/

相关文章:

javascript - createjs.Bitmap() 图像未显示

javascript - 如何在 javascript 中按 id 排序 div?

javascript - 如何设置动态图片路径

javascript - getImageData内存泄漏?

html - block 显示 Canvas 底部仍有间隙

javascript - 尝试在没有 get/putImageData 的情况下操作 Canvas 上的 alpha?

javascript - 在可爱的文件浏览器中复制到剪贴板

javascript - AngularJS:未捕获错误:[$injector:modulerr] 与 firebase

javascript - Canvas 水平旋转图像

javascript - 如何用两个图像保存 Canvas