Rotating the canvas context

The next type of transformation available with the HTML5 canvas API, and quite arguably the handiest, is the rotation transform. In this recipe, we'll first position the canvas context with a translation transform, and then we'll rotate the context with rotate() method.

Rotating the canvas context

How to do it...

Follow these steps to draw a rotated rectangle:

  1. Define the canvas context and the dimensions for the rectangle:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
        
        var rectWidth = 150;
        var rectHeight = 75;
  2. Translate the canvas context and then rotate it by 45 degrees:
     // translate ...

Get HTML5 Canvas Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.