Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html canvas text size not accurate

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" width="500" height="500"></canvas> 
            </body>
</html>
like image 581
puk Avatar asked Dec 18 '25 13:12

puk


1 Answers

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/

like image 82
Simon Sarris Avatar answered Dec 21 '25 02:12

Simon Sarris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!