アニメーションをできるだけスムーズにするには、他のすべての画像を含む画像である CSS スプライトを使用する必要があります。これにより、アニメーションの開始時にすべてのフレームが読み込まれます。
次に、アニメーションをどれだけスムーズにしたいかに基づいて、指定された時間内に関数を呼び出し、画像の背景プロパティを変更するだけです。または、スプライトを使用していない場合は、別の src を割り当てます。
25 以上のフレーム/秒の値を選択する必要があると思います。フレーム レートが高いほど、アニメーションはよりスムーズになりますが、より多くの CPU が使用されます。
これが基本的なアプローチです
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.
}
画像のアニメーションを戻したい場合は、同じアプローチを適用する必要がありますが、フレーム番号は逆になります。