2011-03-27 51 views
3

我想將文本居中放在一個框中,但ctx.measureText()未返回準確的值。當下面的代碼運行時,文本不準確居中。它在谷歌瀏覽器運行的我,但我不能讓它下的jsfiddle(對不起)運行html canvas的文字大小不準確

<html> 
    <head> 
     <script type="text/javascript"> 
      function writeText(){ 
       canvas=document.getElementById('canvas'); 
       ctx = canvas.getContext('2d'); 
       ctx.fillStyle='rgb(250,0,0)'; //red box 
       ctx.fillRect(100,100,300,300); //box of size 200x200 drawn at (100,100) 
       ctx.fillStyle='rgb(0,250,0)'; 

      yOff=0; 
      for (var i=0;i<4;i++){ 
        text="Hello World"; 
       size=20+i*10 
       font='bold '+size+'px serif'; 
        ctx.font=font; 
        ctx.textBaseline='top'; 
        width=ctx.measureText(font,text).width;  
        height=size; 

        x=100+(300-width)/2; //draw inside the rectangle of 100x100 at pos (0,0) 
        y=(300-height)/2+yOff; //draw inside the rectangle of 100x100 at pos (0,0)  
        ctx.fillText(text,x,y); 
       yOff+=50 
      } 
      } 
     </script> 
    </head> 
      <body onload="writeText();" bgcolor="yellow"> 
       <canvas name="canvas" id="canvas" width="500" height="500"></canvas> 
      </body> 
</html> 

回答

4

你不小心測量font字符串,而不是每次都text

measureText只有一個參數,你給它兩個。它應該只是

width = ctx.measureText(text).width;

這是的jsfiddle:

http://jsfiddle.net/PtSAf/19/

+0

哎呀。感謝那。 – puk 2011-03-28 00:46:39