JSFiddle - React, Tailwind, and code Playground

by swesh

HTML

<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="fabric-canvas" width=800 height=800></canvas>

JavaScript

function _wrapText (fabric_canvas, text, x, y, maxWidth, lineHeight) {
    var lines = text.split("\n");
    var wrapped_text = [];
    for (var l = 0; l < lines.length; l++) {
        var line = "";
        var words = lines[l].split(" ");
        for (var w = 0; w < words.length; w++) {
            var testLine = line + words[w] + " ";
            var metrics = fabric_canvas.getContext('2d').measureText(testLine);
            console.log('metric', metrics);
            var testWidth = metrics.width;
            if (testWidth > maxWidth) {
                // add new fabric.Text
                //text_options.top = text_options.top + y;
                wrapped_text.push(line);
                //ctx.fillText(line, x, y);
                line = words[w] + " ";
                //y += lineHeight;
            } else {
                line = testLine;
            }
        }
        //text_options.top = text_options.top + y;
        wrapped_text.push(line);
        //ctx.fillText(line, x, y);
        //y += lineHeight;
    }
    return wrapped_text.join("\n");
  }

  function moveText(text, parent)
  {
    text.set('top', parent.get('top'));
    text.set('left', parent.get('left'));

    text.text = _wrapText(
      canvas,
      text.get('original_text'),
      parent.get('left'),
      parent.get('top'),
      (parent.get('width') * parent.get('scaleX')) / 2,
      20
    );

    console.log(parent);
    console.log(text);

  }

  var canvas = new fabric.Canvas('fabric-canvas');


  var text   = new fabric.Text(
    "Do stuff\n with me! and stuff and stuff and stuff and stuff. And more stuff.and stuff and stuff. And more stuff.and stuff and stuff. And more stuff.and stuff and stuff. And more stuff.and stuff and stuff. And more stuff.",
    {
      original_text: "Do stuff\n with me! and stuff and stuff and stuff and stuff. And more stuff.and stuff and stuff. And more stuff.and stuff and stuff. And more stuff.and stuff and stuff. And more stuff.and stuff and stuff....