wrap text within rect without overflowing it - Javascript Canvas

Javascript examples for Canvas:Text

Description

wrap text within rect without overflowing it

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> 
      <style id="compiled-css" type="text/css">

canvas{/*w w  w . ja va 2s .c om*/
   margin:40px;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
   var canvas = document.getElementById('cv');
   ctx = canvas.getContext('2d');
   var drawMe = function() {
  var img = document.getElementById('bg');
  canvas.width = 364;
    canvas.height = 900;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, 364, 662, 0, 0, 364,662);
ctx.fillStyle = '#E1FFC7';
var rectHeight=50;
text ="Maecenas blandit metus ac pretium tincidunt. Integer lobortis dolor augue, at lacinia lectus ullamcorper nec. Morbi sem est, porta sit amet erat a, faucibus rhoncus mauris. Suspendisse potenti. Mauris pulvinar mollis sagittis. Maecenas ante nisi, sollicitudin eu pretium sed, elementum at eros. In hac habitasse platea dictumst. Sed pretium lorem turpis, a pharetra ex placerat suscipit. Suspendisse vitae nunc vitae nunc viverra pellentesque. Suspendisse dapibus leo vel viverra feugiat. Donec ultricies elementum volutpat. Donec tempus libero arcu. Phasellus aliquam sem et congue consectetur.";
var maxWidth = 220;
      var lineHeight = 25;
      var x = 30;
      var y = 30;
  const words =  text.split(' ');
  ctx.fillRect(20,20,250,words.length*4);
  ctx.fillStyle = 'black';
  drawWords(ctx, text, x, y, maxWidth, lineHeight,rectHeight,words)
  }
   function wrapText(context, text, x, y, maxWidth, lineHeight, rectHeight) {
        var words = text.split(' ');
        return words
      }
  function drawWords(context, text, x, y, maxWidth, lineHeight, rectHeight, words) {
     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);
         rectHeight=rectHeight + lineHeight;
  }
  drawMe();
    });

      </script> 
   </head> 
   <body> 
      <br> 
      <canvas id="cv"></canvas> 
      <img id="bg" src="https://www.java2s.com/style/demo/Google-Chrome.png">  
   </body>
</html>

Related Tutorials