Canvas How to - Rotate text








Question

We would like to know how to rotate text.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){<!-- w w w .j a v a2 s .co  m-->
var canvasWidth;
var canvasHeight;
var interval = 350;
var angleInDegrees = 0;
function init() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext('2d');
    canvasWidth = canvas.width;
    canvasHeight = canvas.height;
    setInterval(function () {
        redraw();
    }, interval);
}
init();
function redraw() {
    angleInDegrees += 5;
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.beginPath();
    ctx.rect(200, 150, 5, 5);
    ctx.fill();
    ctx.save();
    ctx.translate(200, 150);
    ctx.rotate(angleInDegrees * Math.PI / 180);
    ctx.fillStyle = '#f00';
    ctx.font = '40px san-serif';
    ctx.textBaseline = 'top';
    ctx.fillText("Hello rotated", 0, 0);
    ctx.restore();
    ctx.fillStyle = '#f00';
    ctx.font = '40px san-serif';
    ctx.textBaseline = 'top';
    ctx.fillText("Hello still", 0, 0);
}
});//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width=500 height=300></canvas>
</body>
</html>

The code above is rendered as follows: