<title>Canvas 之文字自动换行 — Wrap text into multiple lines in HTML5 Canvas</title>
    <canvas id="myCanvas" width="350" height="500" style="border:1px solid #ccc"></canvas>
    <script src="script.js"></script>
  
      function wrapText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split(' ');
        
        var currentLineText = '';
        var lineNo = 0;
        var tmpCurrentLineText = '';
        
        words.forEach(function(e, i){
  
          tmpCurrentLineText = (tmpCurrentLineText + ' ' + e);
          
          var tmpCurrentLineTextObj = context.measureText(tmpCurrentLineText);
          if (tmpCurrentLineTextObj.width > maxWidth) {
            
            context.strokeText(currentLineText, x, y + lineNo * lineHeight);
            
            lineNo++;
            
            tmpCurrentLineText = e;
            
          }
          currentLineText = tmpCurrentLineText;
          
        });
        // flush the rest texts
        context.strokeText(currentLineText, x, y + lineNo * lineHeight);
        
     
      }
      
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var maxWidth = 340;
      var lineHeight = 30;
      var x = 10;
      var y = 30;
      var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim idasdf sdf asdf asdfsdfsdafsdfdsfdsf asfa dsfads fdsf"
      
      var grd = context.createLinearGradient(0,0, 200, 500);
      grd.addColorStop(0.000, 'rgba(255, 0, 0, 1.000)');
      grd.addColorStop(0.150, 'rgba(255, 0, 255, 1.000)');
      grd.addColorStop(0.330, 'rgba(0, 0, 255, 1.000)');
      grd.addColorStop(0.490, 'rgba(0, 255, 255, 1.000)');
      grd.addColorStop(0.670, 'rgba(0, 255, 0, 1.000)');
      grd.addColorStop(0.840, 'rgba(255, 255, 0, 1.000)');
      grd.addColorStop(1.000, 'rgba(255, 0, 0, 1.000)');
      context.font = '16pt Arial';
      context.strokeStyle = grd;

      wrapText(context, text, x, y, maxWidth, lineHeight);