문제

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 implemented.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top