html5-canvas Rotate an Image or Path around it's centerpoint


Example

enter image description here

Steps#1-5 below allow any image or path-shape to be both moved anywhere on the canvas and rotated to any angle without changing any of the image/path-shape's original point coordinates.

  1. Move the canvas [0,0] origin to the shape's center point

    context.translate( shapeCenterX, shapeCenterY );
    
  2. Rotate the canvas by the desired angle (in radians)

    context.rotate( radianAngle );
    
  3. Move the canvas origin back to the top-left corner

     context.translate( -shapeCenterX, -shapeCenterY );
    
  4. Draw the image or path-shape using it's original coordinates.

     context.fillRect( shapeX, shapeY, shapeWidth, shapeHeight );
    
  5. Always clean up! Set the transformation state back to where it was before #1

  • Step#5, Option#1: Undo every transformation in the reverse order

       // undo #3
       context.translate( shapeCenterX, shapeCenterY );
       // undo #2
       context.rotate( -radianAngle );
       // undo #1
       context.translate( -shapeCenterX, shapeCenterY );
    
  • Step#5, Option#2: If the canvas was in an untransformed state (the default) before beginning step#1, you can undo the effects of steps#1-3 by resetting all transformations to their default state

       // set transformation to the default state (==no transformation applied)
       context.setTransform(1,0,0,1,0,0)
    

Example code demo:

// canvas references & canvas styling
var canvas=document.createElement("canvas");
canvas.style.border='1px solid red';
document.body.appendChild(canvas);
canvas.width=378;
canvas.height=256;
var ctx=canvas.getContext("2d");
ctx.fillStyle='green';
ctx.globalAlpha=0.35;        

// define a rectangle to rotate
var rect={ x:100, y:100, width:175, height:50 };

// draw the rectangle unrotated
ctx.fillRect( rect.x, rect.y, rect.width, rect.height );

// draw the rectangle rotated by 45 degrees (==PI/4 radians)
ctx.translate( rect.x+rect.width/2, rect.y+rect.height/2 );
ctx.rotate( Math.PI/4 );
ctx.translate( -rect.x-rect.width/2, -rect.y-rect.height/2 );
ctx.fillRect( rect.x, rect.y, rect.width, rect.height );