How to rotate image in JavaScript?

In this article, you are going to learn how to rotate an image in JavaScript. In web development, performing images is a simple task.

Either you want to display images in a different adaptation or create interactive image galleries, rotating images constantly using JavaScript is a powerful and practical method.

How to rotate an image in JavaScript?

To rotate images in JavaScript, you can use the HTML5 Canvas element, which offers a powerful 2D drawing API.

Through the Canvas API, you can make a dynamic visual content, including rotating images.

Let’s move on the step-by-step process of rotating an image using JavaScript.

Setting Up the HTML Structure

Before we move on into the JavaScript code, let’s set up first the basic HTML structure.

We can create an HTML file and include an image element that will be rotated dynamically:

Here’s an example code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Rotate Image in JavaScript</title>
</head>
<body>
    <img id="imageToRotate" src="path/to/your/image.jpg" alt="Your Image">
</body>
</html>

You need to replace “path/to/your/image.png” with the actual path to your image file.

Writing the JavaScript Code

Next, add the JavaScript code to rotate the image using the HTML5 Canvas:

Example code:

<script>
    const rotateImage = (degrees) => {
        const image = document.getElementById('imageToRotate');
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');

        // Set canvas dimensions to match the image
        canvas.width = image.width;
        canvas.height = image.height;

        // Clear the canvas
        context.clearRect(0, 0, canvas.width, canvas.height);

        // Rotate the image
        context.save();
        context.translate(canvas.width / 2, canvas.height / 2);
        context.rotate((degrees * Math.PI) / 180);
        context.drawImage(image, -image.width / 2, -image.height / 2);
        context.restore();

        // Replace the original image with the rotated image
        image.src = canvas.toDataURL();
    };

    // Call the function to rotate the image by 90 degrees
    rotateImage(90);
</script>

Testing the Rotation

Now, open the HTML file in your web browser. You will see the image rotated by 90 degrees.

Feel free to adjust the rotateImage function’s parameter to rotate the image by different degrees as per your requirement.

Rotating Image Clockwise and Counterclockwise

Having able to rotate an image in a single direction is applicable, but what if you need to rotate an image both clockwise and counterclockwise?

Let’s change the JavaScript code to add this effectiveness.

Updating the JavaScript Code

<script>
    let rotationAngle = 0;

    const rotateImage = (degrees) => {
        rotationAngle += degrees;

        const image = document.getElementById('imageToRotate');
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');

        // Set canvas dimensions to match the image
        canvas.width = image.width;
        canvas.height = image.height;

        // Clear the canvas
        context.clearRect(0, 0, canvas.width, canvas.height);

        // Rotate the image
        context.save();
        context.translate(canvas.width / 2, canvas.height / 2);
        context.rotate((rotationAngle * Math.PI) / 180);
        context.drawImage(image, -image.width / 2, -image.height / 2);
        context.restore();

        // Replace the original image with the rotated image
        image.src = canvas.toDataURL();
    };

    // Call the function to rotate the image clockwise by 90 degrees
    rotateImage(90);

    // Call the function to rotate the image counterclockwise by 180 degrees
    rotateImage(-180);
</script>

Testing the Rotation

Open the HTML file again in your web browser, and now you will see the image rotated clockwise by 90 degrees and then counterclockwise by 180 degrees.

Creating an Interactive Image Rotator

Creating an interactive image rotator enables users to rotate the image using buttons or controls.

Let’s see the implementation of this functionality.

Enhancing the HTML Structure

Update the HTML structure to include buttons for clockwise and counterclockwise rotations:

Here’s an example code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Rotate Image in JavaScript</title>
</head>
<body>
    <img id="imageToRotate" src="path/to/your/image.jpg" alt="Your Image">
    <button onclick="rotateClockwise()">Rotate Clockwise</button>
    <button onclick="rotateCounterclockwise()">Rotate Counterclockwise</button>
</body>
</html>

Updating the JavaScript Code

<script>
    let rotationAngle = 0;

    const rotateImage = (degrees) => {
        rotationAngle += degrees;

        const image = document.getElementById('imageToRotate');
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');

        // Set canvas dimensions to match the image
        canvas.width = image.width;
        canvas.height = image.height;

        // Clear the canvas
        context.clearRect(0, 0, canvas.width, canvas.height);

        // Rotate the image
        context.save();
        context.translate(canvas.width / 2, canvas.height / 2);
        context.rotate((rotationAngle * Math.PI) / 180);
        context.drawImage(image, -image.width / 2, -image.height / 2);
        context.restore();

        // Replace the original image with the rotated image
        image.src = canvas.toDataURL();
    };

    const rotateClockwise = () => {
        rotateImage(90);
    };

    const rotateCounterclockwise = () => {
        rotateImage(-90);
    };
</script>

Testing the Interactive Image Rotator

Open the updated HTML file in your web browser. Now, you can use the “Rotate Clockwise” and “Rotate Counterclockwise” buttons to interactively rotate the image.

FAQs

Can I rotate an image using CSS instead of JavaScript?

Yes, you can rotate an image using CSS transforms, but it cannot provide dynamic or interactive rotations like JavaScript. CSS transforms are more suitable for static rotations or animations.

How can I rotate an image by a specific angle in JavaScript?

To rotate an image by a specific angle, pass that angle as a parameter to the rotateImage function.

Is it possible to rotate an image based on user input?

Yes, you can rotate an image based on user input. By using event listeners and capturing user actions, you can trigger the image rotation function in response to user interactions.

Conclusion

In this article, we have learned how to rotate images in JavaScript using the HTML5 Canvas element.

Also, we have discussed the basic image rotation concepts, allowed clockwise and counterclockwise rotations, and even implemented an interactive image rotator using JavaScript.

Additional Resources

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.
Adones Evangelista

Programmer & Technical Writer at PIES IT Solution

Adones Evangelista is a programmer and writer at PIES IT Solution, author of over 900 tutorials and error-fix guides at itsourcecode.com. Specializes in JavaScript, Django, Laravel, and Python error debugging covering ValueError, TypeError, AttributeError, ModuleNotFoundError, and RuntimeError, plus C/C++ and PHP capstone projects for BSIT students.

Expertise: JavaScript · Python · Django · Laravel · Error Debugging · C/C++  · View all posts by Adones Evangelista →

Leave a Comment