Rotating an image

In this recipe, we'll rotate an image by translating and rotating the canvas context, and then drawing an image on the transformed context.

Rotating an image

How to do it...

Follow these steps to rotate an image:

  1. Define a canvas context:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
  2. Create a new image object and set its onload property:
        var imageObj = new Image();
        imageObj.onload = function(){
  3. When the image loads, translate the context to the center of the canvas, rotate the context by 45 degrees counter-clockwise, and then draw the image:
     // translate context to center of canvas ...

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.