Arian Faurtosh
Arian Faurtosh

Reputation: 18491

How to center canvas javascript, dynamically based on text length

I want to center "My TEXT!" no matter the length of the string... As the length of the text gets longer, the x coordinate needs to get less.

How can I get the x length of a string?

<html>
    <head>
       <script>
           window.onload = function(){
               var canvas = document.getElementById("myCanvas");
               var context = canvas.getContext("2d");
               var imageObj = new Image();
               imageObj.onload = function(){
                   context.drawImage(imageObj, 0, 0);
                   context.font = "12pt Arial";
                   context.fillText("My TEXT!", 20, 20);
               };
           imageObj.src = "http://images.google.com/intl/en_ALL/images/srpr/logo11w.png"; 
           };
       </script>
    </head>
    <body>
        <canvas width="282px" height="177px" id="myCanvas"></canvas>
    </body>
</html>

Upvotes: 1

Views: 1896

Answers (3)

mlienau
mlienau

Reputation: 813

This should be what you are looking for. http://www.html5canvastutorials.com/tutorials/html5-canvas-text-align/

There's a textAlign property on canvas that you can set to "center". Then start the fill text in the exact middle of the canvas.

EDIT - Here's a fiddle http://jsfiddle.net/mlienau/2MnnC/

Upvotes: 0

Poornima
Poornima

Reputation: 928

Try setting the text alignment.

context.textAlign = "center";
context.fillText("My LONGGGGG TEXT!", (canvas.width)/2, 20);

Upvotes: 1

user1693593
user1693593

Reputation:

Simply add this to your code:

imageObj.onload = function(){
    context.drawImage(imageObj, 0, 0);

    context.font = "12pt Arial";

    /// set text alignment to center
    context.textAlign = 'center';

    /// draw from center
    context.fillText("My TEXT!", canvas.width * 0.5, 20);
};

If you need to get the x coordinate itself you'd need to calculate it based on the width of the text (after the font is set):

var width = context.measureText(myText).width;
var x = (canvas.width - width) * 0.5;

Upvotes: 2

Related Questions