Sunday 3 June 2012

Image Rotation in JavaScript


Image Rotation in JavaScript : 

Script for Rotation :
<script type="text/javascript">
        var interval;
        var Rad = 10;
        function StartRotation() {
            interval = setInterval(start, 150);
        }
        function start() {
          document.getElementById("ImgRotate").style.MozTransform = "rotate(" + Rad + "deg)";                      
          document.getElementById("ImgRotate").style.webkitTransform = "rotate(" + Rad + "deg)";
            Rad += 10;
        }
        function StopRotation() {
            clearInterval(interval);

        }

    </script>



<
img alt="Img" id="ImgRotate" src="Images/DREAM-wall-1024-768.jpg" width="120px"
            height="120px" />
        <br />
        <br />
        <input type="button" value="Start" onclick="StartRotation();" />
        <input type="button" value="Stop" onclick="StopRotation();" />

6 comments:

  1. hello Ajay I'm glad to see this script.. i modified your script a little bit, I changed the degree to be exact 450 degree.. the problem is, can I slow down the speed of the rotation?

    ReplyDelete
    Replies
    1. Thanks

      You can slow down your rotation by increasing Time interval of SetInterval() function


      interval = setInterval(start, 1000);

      Delete
  2. Hi Ajay. I love this little code. I have included it into my webpage with a slight modification to have mouse-over instead of button. I have 2 questions here if you can help. I'm sorry I'm very very bad with Javascript.

    1. How to change the code to include multiple images. Meaning two or more images rotating separately.
    2. How to change the Stop rotating code to rotate to it's original position before stopping.

    I can see a lot of potential to this simple code and if correctly implemented can make a page look more interesting.

    ReplyDelete
    Replies
    1. Thanks For Comment :

      1. you have to write this line for every images.
      document.getElementById("ImgRotate").style.MozTransform
      = "rotate(" + Rad + "deg)";

      For optimization you should take array and fill it with
      image Name and use it in start() function with for loop

      2. When you want to stop to Rotation of Image then Make
      function and Clear Interval. And you have to Save
      original position in variable so when you male stop then
      check for position and then clear the interval

      Delete
  3. how to perform rotate right operation

    ReplyDelete