javascript - Sprite 动画: function not recognized and semi-colon expected in for-loop

标签 javascript function for-loop sprite

我正在开发一个 Sprite 动画项目。鼠标悬停时,控制台日志报告该函数未定义。此外,VS 代码报告了一个错误,即我的 for 循环的最后一个括号内应该有一个分号。

我尝试在 for 循环中添加分号(尽管这对我来说没有意义),并仔细检查所有括号和大括号。

HTML:

</div>

CSS:

#catimage{
height: 256px;
width: 512px;
background: 
url('https://docs.coronalabs.com/images/simulator/sprites-cat- 
running.png')
}

完整的 JS:

var tID;

function catimate() {

    // start position for the image slicer
    var position = 512;
    // 150 ms of interval for setInterval()
    const interval = 150;
    var x = 0;
    var y = 0;
    var catPosition =
    [[0, 0],
        [512, 0],
        [1024, 0],
        [1536, 0],
        [0, 256],
        [512, 256],
        [1024, 256],
        [1536, 256]];

     tID = setInterval(() => {
        document.getElementById("image").style.backgroundPosition = 
       `${x}px ${y}px`;

        for (i = 0, i < catPosition.length, i++) {
            var x = catPosition[i][0];
            var y = catPosition[i][1];
            console.log(x, y);
        }
    }
    , interval);
}

最终我希望通过一个循环来制作这只猫的动画。但是,此时,我只是尝试调用我的函数,然后在鼠标悬停期间查看要在控制台记录的 catPosition 数组中的值。

最佳答案

首先,要使 for 循环工作,您需要在第 24 行使用分号而不是逗号,如下所示 for (i = 0; i < catPosition.length; i++) {

要达到您想要的效果,您可以做的就是在 setInterval 内设置 x 和 y,然后更新 i,而不是每次都通过 for 循环,否则猫只会卡在一个地方。

所以它可能看起来像这样:

var tID;

function catimate() {

    // start position for the image slicer
    var position = 512;
    // 150 ms of interval for setInterval()
    const interval = 150;
    var x = 0;
    var y = 0;
    var i = 0;
    var catPosition =
    [[0, 0],
        [512, 0],
        [1024, 0],
        [1536, 0],
        [0, 256],
        [512, 256],
        [1024, 256],
        [1536, 256]];

     tID = setInterval(() => {
        document.getElementById("image").style.backgroundPosition = `${x}px ${y}px`;

        x = catPosition[i][0];
        y = catPosition[i][1];
        console.log(x, y);

        i++;
    }
    , interval);
}

catimate()

这应该使猫在间隔的每次调用中只移动一个位置。

关于javascript - Sprite 动画: function not recognized and semi-colon expected in for-loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58530354/

相关文章:

javascript - html中选项卡式布局的最佳实践

function - Vim vmap,将选定的文本作为参数发送给函数

python - 遍历包含字典的列表并以某种方式显示它

scala - 具有多个生成器的 for 循环如何在 Scala 中工作?

javascript - jquery animate 不工作,div 不移动

php - 使用 CSS/JS/PHP 在 CodeIgniter 中访问隐藏的无序列表

JavaScript 不会在加载时运行。如何在 HTML 中修复?

javascript - string.length + 计数器变量的使用

c# - 如何将 csharp 绑定(bind)变量传递给 Javascript 函数

python - os.path.isdir() 和 os.path.isfile() 都在脚本中返回 False 但在 Python 控制台中返回 True(就像它们应该的那样)