Fabricjs text example

Displays line breaks from Textarea element, to help keep user formatting.

by Dylan Valentine

HTML

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<textarea id="myInput" type="text">Text displayed
 does now wrap correctly </textarea>
<br>
<canvas id="mycanvas" width="250" height="250"></canvas>

CSS

canvas {
    border: 1px solid black;
}

JavaScript

var canvas = new fabric.Canvas('mycanvas');
canvas.backgroundColor = '#ffff00';
var canvasWidth = 230;
var fontSize_1 = 28;

//from so: http://stackoverflow.com/a/34969600/647485
 function AddTextBreaks(text, width, fontSize) {
    text = text.trim();
    //get existing lines before breaking:
    var lines = text.toString().split('\n'),
        newString = '';
    //for each line, get width of all words
    for(var line=0;  line<lines.length; line++){
        var words = lines[line].toString().split(' '),
            canvas = document.createElement('canvas'),
            context = canvas.getContext('2d'),
            idx = 2;
        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) {
                newString += words.slice(0, idx - 1).join(' ');
                newString += "\n";
                words = words.splice(idx - 1);
                idx = 1;
            }
            else { idx += 1;}
        }
        var txt = words.join(' ');
        newString += txt;
        console.log(line,lines.length);
        //add user linebreaks
        if(line<lines.length-1)
        		newString += '\n';
    }
    return newString;
}

var text = new fabric.Text(AddTextBreaks($('#myInput').val(),canvasWidth,fontSize_1), {
    left: 10,
    top: 12,
    width: canvasWidth,
    textAlign: 'center',
    fontSize: fontSize_1,
    fontFamily: 'Helvetica Nue, Helvetica, Sans-Serif, Arial, Trebuchet MS'
});
$('#myInput').change(function (e) {
    text.text = AddTextBreaks($(this).val(),canvasWidth,fontSize_1);
    text.left = 10;
    text.width = 230,
    canvas.renderAll();
});
canvas.add(text);
canvas.renderAll();