Canvas
Canvas

Reputation: 5897

HTML5 rotate text around it's centre point

I'm having some trouble rotating a piece of text in my canvas by it's centre point, here is my code to attempt my problem

var textPositions = context.measureText(this.Text);

    context.save();

    context.translate(this.XPos + (textPositions.width / 2), this.YPos);
    context.rotate( (Math.PI / 180) * this.RotateSpeed );
    context.font = this.FontSize + "px " + this.FontStyle;
    context.fillText(this.Text, 0, 0);
    context.translate(-(this.XPos + (textPositions.width / 2)), -(this.YPos));

    context.restore();

this.Text is just "Hello world!" this.XPos = 65; this.YPos = 100,

Here is a picture with the non-rotated text and rotated text, enter image description here Am I working out the centre point wrong?

Upvotes: 7

Views: 7239

Answers (1)

markE
markE

Reputation: 105015

Here's one way:

  • Use textAlign & textBaseline to draw the text at it's horizontal and vertical center:

  • translate to the x,y where you want the text centered.

  • rotate by the desired angle

  • And finally fillText

enter image description here

Example code and a Demo: http://jsfiddle.net/m1erickson/uL62et9y/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var cw=canvas.width;
    var ch=canvas.height;

    ctx.beginPath();
    ctx.moveTo(cw/2,0);
    ctx.lineTo(cw/2,ch);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(0,ch/2);
    ctx.lineTo(cw,ch/2);
    ctx.stroke();

    ctx.save();

    ctx.textAlign="center";
    ctx.textBaseline="middle";

    ctx.translate(150,150);
    ctx.rotate(Math.PI/2);
    ctx.fillText("Hello World!",0,0);

    ctx.restore();

}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Upvotes: 10

Related Questions