JSFiddle - React, Tailwind, and code Playground

by Vijay Gujar

HTML

<img src="http://i.imgur.com/8rmMZI3.jpg" id="image" />

<canvas style="border:1px solid red" width="500" height="300" id="myCanvas"></canvas>

JavaScript

var degrees = 90;

function drawRotated(degrees){
    var theImage = document.getElementById('image');
    var imageWidth = theImage.naturalWidth;
    var imageHeight = theImage.naturalHeight;

    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');

    var angle = degrees*Math.PI/180;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // this will align your image in the upper left corner when rotating in 90deg increments
    ctx.translate(Math.abs(imageWidth/2 * Math.cos(angle) + imageHeight/2 * Math.sin(angle)), Math.abs(imageHeight/2 * Math.cos(angle) + imageWidth/2 * Math.sin(angle)));
    ctx.rotate(angle);
    ctx.translate(-imageWidth/2, -imageHeight/2);
    ctx.drawImage(theImage, 0, 0);
}

drawRotated(10);