Fabric.js text width ignored

I am trying to add text to a canvas from form input. Is there a way to automatically wrap fabricjs text to fit inside the canvas?

There are 3 problems that I am trying to overcome: 1. the text does not match the position of text.left if the line is longer than the specified space. 2. I can not escape the lines of a new line, so \ n is written to a line with text. 3. Center-align is completely ignored until the text is updated.

Here is my fabric text:

var text = new fabric.Text($('#myInput').text(), {
    left: 10,
    top: 12,
    width: 230,
    textAlign: 'center',
    fontSize: 28,
    fontFamily: 'Helvetica Nue, Helvetica, Sans-Serif, Arial, Trebuchet MS'
});

A fiddle showing this problem.

How to insert a new line? How to align text by text in this text block? How to place a text block on a canvas without making changes? Strike>

Edit:

, . textarea, . , , .

, , , , . , , , .

wordwrap ?

+4
1

, . , , , ( TextBox). , , .

 function addTextBreaks(text, width, fontSize) {
    text = text.trim();
    var words = text.toString().split(' '),
        canvas = document.createElement('canvas'),
        context = canvas.getContext('2d'),
        idx = 1,
        newString = '';
    context.font = fontSize + 'px Lato';
    while (words.length > 0 && idx <= words.length) {
        var str = words.slice(0, idx).join(' '),
            w = context.measureText(str).width;
        if (w > width) {
            if (idx == 1) {
                idx = 2;
            }
            newString += words.slice(0, idx - 1).join(' ');
            newString += '\n';
            words = words.splice(idx - 1);
            idx = 1;
        }
        else { idx += 1;}
    }
    if (idx > 0) {
        var txt = words.join(' ');
        newString += txt;
    }
    return newString;
}
+5

All Articles