在JavaScript中动画图像数组

时间:2014-03-22 18:52:47

标签: javascript arrays animation jsfiddle

我已经想出了这个使用阵列中的图像的小动画,但它很邋..我真正喜欢的是模块化它,以便我可以使用相同功能的多个实例来根据按下的键来设置不同的数组。另外,我希望得到它,以便在释放密钥时动画停止,如果可能的话。我意识到全局调用所有这些变量是一个很大的禁忌,但我不知道如何使其工作!最后但并非最不重要的是,我想弄清楚如何将最后一行内联脚本放到外部文件中并让它仍能正常工作。任何帮助将非常感激!但是请注意,我是JavaScript的新手,所以请尽量做到具体/详细,这样我才能从你的智慧中学习!谢谢!

我创建了一个jsfiddle here

<div id="wrapper"> <span id="jajo"><img id="my_img" src="http://www.mouserunner.net/free_graphics/Web_2_0/Flowers/Flowers_Preview_P.png" /></span>
    <script>
        element = document.getElementById("jajo");
    </script>
</div>


var i = 0;
var element;
var waveArray = ["http://static.spoonful.com/sites/default/files/styles/square_128x128/public/crafts/fingerprint-flowers-spring-craft-photo-420x420-aformaro-01.jpg", "http://static.spoonful.com/sites/default/files/styles/square_128x128/public/crafts/paper-flowers-spring-craft-photo-420x420-aformaro-11.jpg", "http://static.spoonful.com/sites/default/files/styles/square_128x128/public/crafts/tissue-paper-flowers-kaboose-craft-photo-350-fs-IMG_8971_rdax_65.jpg"];
var jumpArray = ["jump0.png", "jump1.png", "jump2.png", "jump3.png", "jump4.png", "jump5.png"];
var foodArray = ["food0.png", "food1.png", "food2.png", "food3.png", "food4.png", "food5.png"];

document.onkeydown = function (event) {
var keyPress = String.fromCharCode(event.keyCode);

if (keyPress == "W") { // if "w" is pressed, display wave animation
    increment();

    document.onkeyup = function (event) { // if "w" is released, display default image
        document.getElementById("jajo").innerHTML = "<img alt='Jajo' src='http://www.mouserunner.net/free_graphics/Web_2_0/Flowers/Flowers_Preview_P.png'>";
    }
} else if (keyPress == "A") { // if "a" is pressed, display jump animation
} else if (keyPress == "S") { // if "s" is pressed, display food animation
}
}

function increment() {
i++;
if (i > (waveArray.length - 1)) {
    i = 0;
}
setTimeout(animation, 1000 / 30);
}


function animation() {
var img = '<img src="' + waveArray[i] + '" alt="Jajo" />';
element.innerHTML = img;
setTimeout(increment, 2000 / 30);
}

0 个答案:

没有答案