I am trying to center text in a box, but the ctx.measureText() is not returning accurate values. When the below code is run, the text is not accurately centered. It runs for me under google chrome, but I couldn't get it to run under jsfiddle (sorry)
<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" wi开发者_运维技巧dth="500" height="500"></canvas> 
            </body>
</html>
You are accidentally measuring the font string instead of text each time!
measureText has only one argument and you are giving it two. It should just be
width = ctx.measureText(text).width;
Here it is in jsfiddle:
http://jsfiddle.net/PtSAf/19/
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论