JSFiddle - React, Tailwind, and code Playground

by wizztjh

HTML

<canvas id="cvs"></canvas><br />
<input type="text" id="input" />

CSS

body { 
 background-color: #efefef;   
}
canvas { 
 outline: 1px solid #000;   
 background-color: white;
}

JavaScript

var canvas = document.getElementById('cvs'),
    ctx = canvas.getContext('2d'),
    input = document.getElementById('input'),
    width = +(canvas.width = 400),
    height = +(canvas.height = 250),
    fontFamily = "Arial",
    fontSize = "24px",
    fontColour = "blue";

function wrapText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split(" ");
        var line = "";
        for(var n = 0; n < words.length; n++) {
          var testLine = line + words[n] + " ";
          var metrics = context.measureText(testLine);
          var testWidth = metrics.width;
          if(testWidth > maxWidth) {
            context.fillText(line, x, y);
            line = words[n] + " ";
            y += lineHeight;
          }
          else {
            line = testLine;
          }
        }
        context.fillText(line, x, y);
}

function draw() {
    ctx.save();
    ctx.clearRect(0, 0, width, height);
    //var lines = makeLines(input.value, width - parseInt(fontSize,0));
    //lines.forEach(function(line, i) {
    //    ctx.fillText(line, width / 2, height - ((i + 1) * parseInt(fontSize,0)));
    //});
    wrapText(ctx, input.value, x, y, (canvas.width - 8), 25)
    ctx.restore();
}

input.onkeyup = function(e) { // keyup because we need to know what the entered text is.
    draw();
};

   var text = "HTML5 Wrap Text functionsdfasdfasdfsadfasdfasdfasdfasdfasdf in Javascript written here is helped me a lot.";
   var x = 20;
   var y = 20;
   wrapText(ctx, text, x, y, (canvas.width - 8), 25)