Skip to content

Rotating Images in JavaScript: Three Quick Tutorials

With JavaScript (JS), you can create cool image animations, which are difficult to do with Cascading Style Sheets (CSS). This article describes how to—

  • Dynamically rotate or flip images with JS.
  • Automatically rotate and remove image backgrounds with Cloudinary.

Here are the topics:

To rotate images with JS, edit the CSS transform property. See the procedure below.

First, define the image element in your HTML source and create a clickable element, which can be a button or the image itself. For example:

HTML

<img class="rotate" src="image.jpg"/>

JS file or <script> element

Next, define a rotational variable to maintain the image rotation, enabling multiple rotations, as here:

const current_rotation = 0;

Finally, add an event listener to the image (see the code below). In the listener function, incrementing the rotation with positive numbers rotates the image in a clockwise direction; doing that with negative numbers results in a counterclockwise rotation.

document.querySelector(".rotate").addEventListener('click', function(){
	current_rotation += 90;
document.querySelector(".rotate").style.transform = 'rotate(' + current_rotation + 'deg)';
});

When applying rotations, you can add CSS properties to animate rotations or set up rotations around a specific point of the image.

Animations

To animate rotations, apply the CSS transition property to specify which other property is transitioned and when. For example, the following code causes the rotation to occur in half a second with a slow start.

.rotate {
	transition: transform 0.5s ease-in;
}

Rotation point

By default, the image rotates around its center point. To have the image rotate around another point, specify that point with the transform-origin property in CSS.

If manually defined, the center point is at 50% 50%. You can alter the x and y values for 2D images, and the z value for 3D images. For example:

To set the origin in the upper-right corner:

.rotate {
	transform-origin: 100% 0%;
}

To set the origin in the upper-left corner:

.rotate {
	transform-origin: 0% 0%;
}

For more cool tricks, see our articles on resizing with JavaScript and with CSS.

Flipping or mirroring images is a common task. Displaying mirrored images with ‘transform: scaleX(-1’)in CSS is just an effect, not a permanent change. To persistently flip an image for static use, create a canvas in JS to transform and output the image after flipping.

The code examples below are adapted from a tutorial by Rik Schennink.

HTML

First, define the image element:

<img src="image.jpg" class="image-flip"/>

JS file or <script> element

Next, create a reference to your image for transformations with a canvas:

const inputImage = document.querySelector('.image-flip');

Add logic to ensure that the flipping occurs at the right time. The code below first checks if image loading is complete and, if so, the flip function runs. Otherwise, the function waits till loading is done before flipping the image.

if (inputImage.complete) {
  flipImage();
}
else {
  inputImage.onload = flipImage;
}

Now create a function that flips the image—in effect, create a canvas, set it to the same size as the image, and define your drawing context. You can then flip the image with ctx.scale(), draw the image on the canvas with ctx.drawImage, and display the output image with insertBefore() on the appropriate Document Object Model (DOM) element. Here’s the code:

function flipImage() {
    
  const outputImage = document.createElement("canvas");
  outputImage.width = inputImage.naturalWidth;
  outputImage.height = inputImage.naturalHeight;
    
  const ctx = outputImage.getContext("2d");

  // Flip the image by scaling negatively to the left
  ctx.scale(-1, 1);

  // Draw the image on the canvas
  // Starts at [-width, 0] because the flip scaled negatively
  ctx.drawImage(inputImage, -outputImage.width, 0);
    
  // Display the output image after the input image in your client
inputImage.parentNode.insertBefore(outputImage, inputImage.nextElementSibling);
}

For details on transforming images with CSS, see this article on CSS image effects.

A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload your images, apply built-in effects, filters, and modifications, including automated image rotations that are difficult or impossible to produce with CSS and JS.

Also with Cloudinary, you can easily transform images programmatically with SDKs or URL parameters. Cloudinary applies changes dynamically, leaving your original images intact. That means you can modify images on the fly as your site design evolves and as you support more devices and screen sizes—a huge convenience and time saver.

Below are two ways in which to rotate images with Cloudinary.

To automatically rotate and flip videos, set the angle parameter (‘a_’) with a numerical value. To mirror videos, set the ‘vflip’ (for vertical flips) or hflip (for horizontal flips) parameter. Here’s an example of a video mirrored vertically:

cloudinary.videoTag('dog', {angle: “vflip”, width: 500}).toHtml();

If the angle skews the display with bounding boxes around the video, select the color of the boxes and display a blurred version of the video in that space. See this example of a video with white bounding boxes.

cloudinary.videoTag('dog', {angle: 20, width: 500}).toHtml();

By leveraging Cloudinary’s machine-learning features, you can remove image backgrounds and rotate the image itself. That’s a neat way for creating product mockups or customizing images.

To remove the background, use Cloudinary’s AI Removal Background add-on with which you can upload images with Ruby, PHP, Python, Java, .NET, or Node.js, and assign output URLs. Below is an example in Node.js:

cloudinary.v2.uploader.upload("baseball.jpg", 
  { public_id: "baseball_no_bg",
    background_removal: "cloudinary_ai",
    notification_url: "https://mysite.example.com/hooks" }),
  function(error, result){console.log(result);});
These:

Become These!

Baseball player - original

baseball player - no background

Afterwards, you can flip or rotate the backgroundless image as you desire. The example below rotates it by 60 degrees clockwise.

baseball

cloudinary.imageTag('baseball.png', {transformation: [
  {width: 500 },
  {angle: 60 }
  ]}).toHtml();

baseball

Besides image rotations, Cloudinary offers a multitude of robust tools for web developers, including the following:
  • Automated image uploads. You can upload images at scale anywhere from a browser, mobile app, or application back-end directly to the cloud.
  • Generous image storage. Cloudinary accords you up to 25 GB free managed, secure, and cloud-based storage space with multiregion backup, revision history, and disaster recovery.
  • Seamless asset management. You can efficiently manage your image library on Cloudinary by performing tasks like searching, organizing, and tagging files; controlling access; and monitoring usage and performance.
  • Effective image transformations. You can transform, enhance, transcode, crop, scale, and enhance images with a URL-based API or with SDKs that support all popular programming languages.
  • Automated image optimization. Cloudinary automatically selects the optimal quality and encoding settings for images, adapts the settings to any resolution or pixel density, and scales or crops images to focus on the important regions.
  • Responsive images. Cloudinary automatically scales images in an art-directed manner, cropping them to fit different resolutions and viewports.
  • Reliable and fast image delivery. Cloudinary delivers images through Content Delivery Networks (CDNs)—Akamai, Fastly, and CloudFront—with no integration or management on your part.

Do give Cloudinary a try. To start, sign up for a free account.

Want to learn more about CSS image transformations? These articles are an excellent resource:

Back to top

Featured Post