broken text in new lines
broken text in new lines when the width of the text reach the original width bounding box.
HTML
<script src="https://raw.github.com/kangax/fabric.js/master/dist/all.js"></script>
<textarea id="textArea"></textarea>
<br/>
<canvas id="c" width="600" height="400"></canvas>
CSS
canvas {
border-width: 1px;
border-style: solid;
border-color: #000;
margin: 5px;
}
JavaScript
// canvas
var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
stroke: '#DDDDDD',
strokeWidth: 1,
fill: false,
top: 200,
left: 300,
width: 330,
height: 260,
selectable: false
});
canvas.add(rect);
var text = new fabric.Text("text text text text text\n" +
"text text text text text\n" +
"text text text text text\n" +
"text text text text text\n" +
"text text text text text", {
fill: '#000000',
top: 200,
left: 300
});
canvas.add(text);
canvas.renderAll();
var widthBoundingBox = text.getBoundingRectWidth();
var heightBoundingBox = text.getBoundingRectHeight();
console.log(widthBoundingBox, heightBoundingBox);
var oldText = text.get("text");
var newText = text.get("text");
var start = 0;
$("#textArea").keyup(function (evt) {
oldText = text.get("text");
text.set("text", this.value);
newText = text.get("text");
if (text.get("height") > heightBoundingBox) {
text.set("text", oldText);
}
else {
if (text.get("width") > widthBoundingBox) {
var lastIndex = newText.lastIndexOf(" ");
newText = newText.substring(0, lastIndex) + "\n" + newText.substring(lastIndex+1);
text.set("text", newText);
$("#textArea").val(newText);
}
else{
}
}
canvas.renderAll();
});