I am learning HTML5 and JavaScript and am attempting to draw an animated image. I thought the easiest way to do this would be to create an image with the frames in a row, as below.
Image http://html5stuff.x10.mx/HTML5%20Test/alien_green_strip8.png
Then a only part of the image would be draw at a time. I followed this tutorial.
This is a link to what I have made:
html5stuff.x10.mx/HTML5%20Test/page.html
The problem is, the image isn’t being drawn. It’s something within the drawSprite function, because when I change it to a simple “ctx.drawImage(sprite.source, x, y)”, it does draw the image (just as a whole without the animation, obviously). Please note that though there is an option for rotating the image, I have not yet added support for that. Also, keys.js is not being used yet though it is included.
The reason is because
sprite.imagenumis not defined whendrawSpriteis called.This is because in some places you use
imagenumand othersimgnum, so correct that typo and you’re good to go!TOTALLY OPTIONAL:
But now that thats answered lets take a look at your js to get a better idea of how to structure this. You have:
All those var statements are actually doing nothing. It should be:
in order to correctly set them as you were envisioning. Also, you can rewrite drawSprite so that the sprites are drawing themselves, so that you don’t need to pass them as an argument:
Then instead of:
We can write: