JSFiddle - React, Tailwind, and code Playground

by IceCreamYou

HTML

<div>
    <button id="clockwise">Rotate right</button>
    <button id="counterclockwise">Rotate left</button>
</div>

CSS

body {
    background-color: ivory;
}

canvas {
    border: 1px solid red;
    margin-top: 10px;
    width: 20%;
}

JavaScript

// Demo interaction

(function() {
    var angleInDegrees = 0,
        image = document.createElement("img"),
        canvas;
    image.onload = function() {
    		canvas = drawRotated(image, 0);
        document.body.appendChild(canvas);
    };
    image.src='http://greekgear.files.wordpress.com/2011/07/bob-barker.jpg';

    $('#clockwise').click(function() { 
        angleInDegrees = (angleInDegrees + 90) % 360;
        drawRotated(image, angleInDegrees, canvas);
    });
    $('#counterclockwise').click(function() { 
        if (angleInDegrees === 0) angleInDegrees = 270; // Wrap to avoid -90
        else angleInDegrees = (angleInDegrees - 90) % 360;
        drawRotated(image, angleInDegrees, canvas);
    });
})();

// Reusable function

/**
 * Returns a canvas containing an image rotated by an increment of 90 degrees.
 *
 * @param {HTMLImageElement} image
 *   The image to rotate.
 * @param {Number} degrees
 *   One of 0, 90, 180, or 270. The degrees by which the image should be rotated.
 * @param {HTMLCanvasElement} [canvas]
 *   A canvas onto which to draw the image. The canvas will be cleared. If not passed, a new canvas will be created.
 *
 * @return {HTMLCanvasElement}
 *   A canvas with the specified image drawn on it with the given rotation.
 */
function drawRotated(image, degrees, canvas) {
    if (!canvas) {
    		canvas = document.createElement('canvas');
    }
    var context = canvas.getContext('2d');

		// Make the canvas dimensions fit the image. This also clears the canvas and resets its transformation matrix.
    if (degrees === 90 || degrees === 270) {
        canvas.width = image.height;
        canvas.height = image.width;
    }
    else {
        canvas.width = image.width;
        canvas.height = image.height;
    }

		// Rotate around the center of the image (by default the canvas rotates around the upper-left corner).
		context.translate(canvas.width * 0.5, canvas.height * 0.5);
    context.rotate(degrees * Math.PI/180);
    // Draw the...