【问题标题】:html canvas text size not accuratehtml画布文本大小不准确
【发布时间】:2011-07-24 02:47:26
【问题描述】:

我正在尝试将文本居中放置在一个框中,但 ctx.measureText() 没有返回准确的值。运行以下代码时,文本未准确居中。它在 google chrome 下为我运行,但我无法让它在 jsfiddle 下运行(对不起)

<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>

【问题讨论】:

    标签: html text canvas width


    【解决方案1】:

    您每次都意外地测量了font 字符串而不是text

    measureText 只有一个参数,你给它两个。应该只是

    width = ctx.measureText(text).width;

    在 jsfiddle 中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多