cycle through animations on click

2019-09-04 02:17发布

问题:

starting with a single image, I have three animations I want it to cycle through each time the image is clicked. I created this switch:

function switcher() {
// counts to 4 then resets to 0
x = x+1
if (x>3) {x = 0}

// Fire OFF
if (x == 0) {
    // animation code ?
}

// Fire LARGE
if (x == 1) {
// animation code ?    
}

// Fire MEDIUM
if (x == 2) {
// animation code ?
}

// Fire SMALL
if (x == 3) {
// animation code ?
}}

1 static state + 3 animated states.

The animation I have uses Paul Irish's requestAnimframe Polyfill then:

function animate() 
    {   
    setTimeout(function()
        {
        requestAnimFrame( animate );        
        draw();   
        }, 1000 / 2);
    } 

function draw()    
    {   
    flame=document.getElementById('myimage')
    if (flame.src.match("Images/lfire1.png"))
        {
        flame.src="Images/lfire2.png";
        }
    else
        {
        flame.src="Images/lfire1.png";
        }     
    }   

each animation is basically this same code but with different Images. The code works when I test it directly but when I copy into the switch it won't work.

I have tried to plug these into my switch using multiple methods and can't seem to get anything to work. any tips? Thank you!

回答1:

I am unclear as to how you are calling the switcher() method but I suspect that the problem may have to do with the way Javascript handles setTimeout().

Keep in mind that when you call setTimeout() in Javascript that the script itself does not halt until your timeout is ended. Instead, it spawns a process to deal with the specified timeout and then continues chugging through your code.

If you chain your animations using one method and a counter(something persisted across calls to the method) such that when the method is called it performs it's animation and then checks if the counter is less than 2 before it calls itself again using setTimeout(), you should be ok.

Sorry if I'm off base here. Operating on a significant assumption: You are using setTimeout() to call switcher().

I hope this helps.