1

I'm using the below code to wrap the input to a textarea in a small web-based application I'm working on.

I would like the positioning of an element further down the page to be dependent on the number of lines the text takes up.

Can anyone suggest a means of determining the number of lines the text takes up, and defining it as a variable?

Thanks.

JavaScript

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 && n > 0) {
        context.fillText(line, x, y);
        line = words[n] + ' ';
        y += lineHeight;
      }
      else {
        line = testLine;
      }
    }
    context.fillText(line, x, y);
  }

  var size = document.getElementById("bgSize").value;
  var maxWidth = (canvas.width * (size / 100)) - (canvas.width * ((size / 100) * 0.15));
  var alignment = document.getElementById("bgAlign").value;
  if(alignment > 0){
      var x = 1280-(size * 6.4);
  }else{
      var x = size * 6.4;
  }
  var y = 160;
  var textContent = document.getElementById("textContent").value;
  var text = textContent;

  var colourInput = document.getElementById("bgColour").value;
  if(colourInput > 0){
      var textColour = '#fff';
  }else{
      var textColour = '#415055';
  }

  var fontSizeInput = 40;
  var maxFontSize = 60;
  var fontSize = fontSizeInput;
  context.font = ''+fontSize+'pt gillsans';
  context.fillStyle = textColour;
  context.textAlign = "center";

  var lineFactor = 1.35;
  var lineHeight = fontSize * lineFactor;

  wrapText(context, text, x, y, maxWidth, lineHeight);
Tom Davies
  • 151
  • 1
  • 8
  • Possible solution here: http://stackoverflow.com/questions/1760629/how-to-get-number-of-rows-in-textarea – nem035 Sep 09 '15 at 14:00

0 Answers0