开发者

Animating image sequence with JavaScript

I have a sequence with images of an object from different angles. I want the object to be faux rotated when the user drags its mouse, and this I have implement开发者_如何学Ced.

But what I want, is when the mouse leaves the image area, that it animates the image sequence back to the default position.

For instance, I have 30 JPEGs, where 1.jpg is -180° and 30.jpg is 180°. Naturally, 15.jpg is the centered default image at 0°.

So, if the user rotates all the way to (-)180° it will rotate back to 0° after say 3 seconds. But I want the animation to be as smooth as possible. How would I go about to do this?


For the animation to be as smooth as possible, you should use a CSS sprite, an image containing all your other images, so the frames will all be loaded when the animation start.

Then you only need to call a function in a given amount of time, based on how smooth you want the animation to be, and change the background property of your image. Or, if not using sprite, assign a different src to it.

I think you should choose a frame-per-second value of no less than 25. Higher frame rate means more smooth animation, but more CPU used.

This is the basic approach

function next_frame() {

  frame += 1;

  // start animation again from the start if last frame reached (optional)
  if ( frame == max_frames ) {
    frame = 0;
  }

  /* change either the class of your image (if you use sprites
     and specified a class for each background position) or the
     background position property directly. If not using sprites,
     assign a different image src based on current frame.
  */

  // call the function again
  setTimeout( next_frame, 1000 / 25 ); // change 25 with your desired FPS value.

}

If you want the image to animate back, you just need to apply the same approach but with the frame numbers going backwards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜