I am trying to create an animation with a few images in javascript and I have the code working, but after it runs through images in reverse then it pauses slightly before it starts going forward again. I'm wondering how I get rid of the pause?

Here is the code in action http://isogashii.com/projects/javascript/ch10/dp10-6.html

HTML

<img id="pin" src="assets/pin0.gif" alt="pin animation" />

Javascript

var pin = new Array(9);
var curPin = 0;
var x = false;

// caching images
for (var imagesLoaded=0; imagesLoaded < 9; ++imagesLoaded) {
    pin[imagesLoaded] = new Image();
    pin[imagesLoaded].src = "assets/pin" + imagesLoaded + ".gif";

    //starts pinF function when all images are cached
    if (imagesLoaded == 8) {
        setInterval("pinF()", 120);
    }
}

function pinF() {

    if (x == true) {
        --curPin;
        if (curPin == 0) {
            x = false;
        }
    }
    if (x == false) {
        ++curPin;
        if (curPin == 8) {
            x = true;
        }
    }

    document.getElementById("pin").src = pin[curPin].src;
}
有帮助吗?

解决方案

in the x == true portion of the if statement, you should set the curPin to be one otherwise you are duplicating the curPin = 1.

http://jsfiddle.net/A77cx/

function pinF() {

    if (x == true) {
        --curPin;
        if (curPin == 0) {
            curPin = 1;
            x = false;
        }
    }
    if (x == false) {
        ++curPin;
        if (curPin == 8) {
            x = true;
        }
    }

    document.getElementById("pin").src = pin[curPin].src;
}

其他提示

Currently, you do two "frames" of pin1. Change the logic of pinF not to do that.

To be specific, the first time x == true and curPin == 2, the first if executes, reducing curPin to 1.

The second time, x == true still, the first if brings curPin down to 0 and inverts x. Then, the second if increments curPin back to 1.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top