https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c8336cc4-765c-4b66-a415-75772dea9932/Untitled.png

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

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 );