Dynamically Rotating an Image using Javascript

Published on January 15, 2020

An image can be rotated with Javascript by dynamically changing its CSS transform property. The point around which rotation needs to happen can be specified with the transform-origin property.

Rotating an image with Javascript can happen by changing its CSS transform property and using the rotate transformation function.

Example

HTML

<img id="sample" src="img/javascript-logo.jpg" />
<button id="rotate-button">Rotate</button>

Javascript

// we need to save the total rotation angle as a global variable 
var current_rotation = 0;

// change CSS transform property on click
document.querySelector("#rotate-button").addEventListener('click', function() {
	// update total rotation
	// if angle is positive, rotation happens clockwise. if negative, rotation happens anti-clockwise.
	current_rotation += 90;

	// rotate clockwise by 90 degrees
	document.querySelector("#sample").style.transform = 'rotate(' + current_rotation + 'deg)';
});

Showing Rotation as an Animation

The rotation performed can be shown as an animation by using the CSS transition property, or the animation property (for more specific animations).

/* apply transition on the translate property */
#sample {
	transition: transform 0.3s;
}

Specifying the Rotation Point

By default rotation happens around the center point of the element. To rotate the image about some other point, the CSS transform-origin property needs to be changed.

/* by default transform origin is set to (50% 50%) which is the center position */

/* set transform origin to the top-left corner */
#sample {
	transform-origin: 0% 0%;
}

/* set transform origin to the bottom-right corner */
#sample {
	transform-origin: 100% 100%;
}

/* set transform origin to the bottom-left corner */
#sample {
	transform-origin: 0% 100%;
}
Loading Comments