2011-06-29 24 views
6

我該如何調整一個HTML5畫布中的文字來證明「?在下面的代碼,文本可以左/右/中心對齊。我需要設置align="justify",請建議如何才能做到這一點?如何證明對齊HTML5畫布中的文本?

HTML :

<body onload="callMe()"> 
    <canvas id="MyCanvas"></canvas> 
</body> 

JS:

function callMe() { 
    var canvas = document.getElementById("MyCanvas"); 
    var ctx = canvas.getContext("2d"); 
    var txt = "Welcome to the new hello world example"; 
    cxt.font = "10pt Arial"; 
    cxt.textAlign = "left"; 

    /* code to text wrap*/ 
    cxt.fillText(txt, 10, 20); 
} 
+0

有趣的問題:)。它會幫助一點,但如果你想更多地格式化你的問題,特別是代碼位;) – Jeroen

回答

2

HTML5的畫布不支持多行文字繪圖所以對齊類型沒有實際效果。

如果你想支持線的飼料,你必須自己支持它,你可以看到在這裏先前討論:HTML5 Canvas - can I somehow use linefeeds in fillText()?

這是我實現了自動換行/換行:

function printAtWordWrap(context, text, x, y, lineHeight, fitWidth) { 
     fitWidth = fitWidth || 0; 
     lineHeight = lineHeight || 20; 

     var currentLine = 0; 

     var lines = text.split(/\r\n|\r|\n/); 
     for (var line = 0; line < lines.length; line++) { 


      if (fitWidth <= 0) { 
       context.fillText(lines[line], x, y + (lineHeight * currentLine)); 
      } else { 
       var words = lines[line].split(' '); 
       var idx = 1; 
       while (words.length > 0 && idx <= words.length) { 
        var str = words.slice(0, idx).join(' '); 
        var w = context.measureText(str).width; 
        if (w > fitWidth) { 
         if (idx == 1) { 
          idx = 2; 
         } 
         context.fillText(words.slice(0, idx - 1).join(' '), x, y + (lineHeight * currentLine)); 
         currentLine++; 
         words = words.splice(idx - 1); 
         idx = 1; 
        } 
        else 
        { idx++; } 
       } 
       if (idx > 0) 
        context.fillText(words.join(' '), x, y + (lineHeight * currentLine)); 
      } 
      currentLine++; 
     } 
    } 

有沒有支持對齊或理由在那裏,你必須添加它在

+0

我可以基於換行符打斷一個句子,並將其餘的文本放在下一行(即多行)我可以對齊它以中心/右/左使用textAlign。但我無法對齊它的理由.. – Sangam254

+0

謝謝你的代碼..但我需要幫助來證明文字 – Sangam254

+1

Yuo cna利用這種調整算法:https://www.rose- hulman.edu/class/csse/csse221/200910/Projects/Markov/justification.html應該很容易在canvas中實現 – Variant