fabric js text wrap
This code snippet implements text missing wrap feature in fabric js.
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.1.0/fabric.all.min.js"></script>
<textarea id="addNote"></textarea>
<canvas id="c" width="400" height="400"></canvas>
JavaScript
var canvas = new fabric.Canvas('c');
canvas.backgroundColor = "#F5F5F5";
textArea = document.getElementById('addNote');
canvas.observe('object:selected', function (e) {
console.log(1);
oldStateObject = $.extend(true, {}, e.target);
oldStateObject.width = oldStateObject.currentWidth;
oldStateObject.height = oldStateObject.currentHeight;
var activeObject = e.target;
if (activeObject.type == 'text') {
textArea.value = activeObject.text;
}
});
function wrapCanvasText(t, canvas, maxW, maxH) {
if (typeof maxH === "undefined") {
maxH = 0;
}
// var words = t.text.split(" ");
var words = t.split(" ");
var formatted = '';
// clear newlines
// var sansBreaks = t.text.replace(/(\r\n|\n|\r)/gm, "");
var sansBreaks = t.replace(/(\r\n|\n|\r)/gm, "");
// calc line height
var lineHeight = new fabric.Text(sansBreaks, {
fontFamily: t.fontFamily,
fontSize: 25 //t.fontSize
}).height;
// adjust for vertical offset
var maxHAdjusted = maxH > 0 ? maxH - lineHeight : 0;
var context = canvas.getContext("2d");
context.font = t.fontSize + "px " + t.fontFamily;
var currentLine = "";
var breakLineCount = 0;
for (var n = 0; n < words.length; n++) {
var isNewLine = currentLine == "";
var testOverlap = currentLine + ' ' + words[n];
// are we over width?
var w = context.measureText(testOverlap).width;
if (w < maxW) { // if not, keep adding words
currentLine += words[n] + ' ';
formatted += words[n] += ' ';
} else {
// if this hits, we got a word that need to be hypenated
if (isNewLine) {
var wordOverlap = "";
// test word length until its over maxW
for (var i = 0; i < words[n].length; ++i) {
wordOverlap += words[n].charAt(i);
var withHypeh = wordOverlap + "-";
...