雪碧表不起作用

时间:2016-10-30 21:04:23

标签: javascript html canvas sprite-sheet

所以我使用在线教程(onlyWebPro.com)让我的圣诞老人在我的屏幕上运行。但它只是不会移动。我使用的是frameCount,所以我不知道为什么它不会移动。谁能帮我?我很容易,我是学生。

<html>
<head>
    <meta charset="UTF-8" />
    <title>Santa</title>
</head>
<body>
    <canvas id="myCanvas" width="1000" height="1000">
        Sorry, your browser doesn't support canvas technology
    </canvas>
<script>
    var width = 100,
            height = 100,
            frames = 5,

            currentFrame = 0,

            canvas = document.getElementById("myCanvas");
            ctx = canvas.getContext("2d");
            image = new Image()
            image.src = 'img/santa-run-sequence.png';

    var draw = function(){
            ctx.clearRect(0, 0, width, height);
            ctx.drawImage(image, 390, 1, 128.333, 210, 100, 500,  128.333, 210);

            if (currentFrame == frames) {
              currentFrame = 0;
            } else {
              currentFrame++;
            }
    }

    setInterval(draw, 100);

</body>
</html>

1 个答案:

答案 0 :(得分:1)

您已获得此行中图片位置的硬编码值:

ctx.drawImage(image, 390, 1, 128.333, 210, 100, 500,  128.333, 210);

相反,您可以添加xy个变量,这些变量会在每个帧中增加。让我们修改您的draw函数以执行以下操作:

ctx.drawImage(image, x, y, 128.333, 210);

if (currentFrame == frames) {
  currentFrame = 0;
} else {
  x += 5
  y += 5
  currentFrame++;
}

另外,不要忘记在脚本标记之上定义xy

var x = 10; // start X position
var y = 10; // start Y position