Example of HTML5 canvas context rotate

Example of canvas rotate rotate() rotates around the canvas' origin (width/2,height/2) therefore we translate the context to the center of the canvas before the rotation so that the rotation is about the center (and translate back afterwards).

by user2314737

HTML

<canvas id="canvas" width=240 height=240 style="background-color:#808080;">
</canvas>

<button type="button" onclick="rotate_ctx();">Rotate context</button>

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ox = canvas.width / 2;
var oy = canvas.height / 2;
ctx.font = "42px serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#FFF";
ctx.fillText("Hello World", ox, oy);

rotate_ctx = function() {
  // convert degrees to radians with radians = (Math.PI/180)*degrees. 
  ctx.translate(ox, oy);
  ctx.rotate((Math.PI / 180) * 15);
  ctx.fillText("Hello World", 0, 0);
  ctx.translate(-ox, -oy);
};