M.MFG
M.MFG

Reputation: 11

Sprite sheet won't work

So I used an online tutorial (onlyWebPro.com) to make my Santa Claus run over my screen. But it just won't move. I'm using a frameCount so I don't really get why it isn't moving. Can anyone help me? Please be easy on me, I'm a student.

<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>

Upvotes: 1

Views: 93

Answers (1)

Selenir
Selenir

Reputation: 718

You've got hardcoded values for position of the image in this line:

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

Instead you could add x and y variables, which would be increased in each frame. Let's modify your draw function to do the following:

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

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

Also don't forget to define x and y on top of your script tag:

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

Upvotes: 1

Related Questions