Sprite Animation in JavaScript (part 1)

Today I’m followed TK tutorial to do a sprite animation by JavaScript. To get ready to do a sprite animation, I have to download “Kat.png” and “sprite sheet.png” in TK’s Github. Next we created 3 files: “index.html”, “script.js”, “style.css”. Set the title “Sprite Animation” and link the “style.css” and “script.js” with the “index.html” and create a canvas with id is “myCanvas”. And we style it in the “style.css” file. You will receive a square on the screen like below.

Create “img” folder and add “cat.png”, “sprite sheet.png” to it. Load the sprite sheets image have id is “myImg” in the “index.html” file . In the “script.js” file, create a canvas variable equal get element by id “myCanvas”. Create a img equal get element by id “myImg” and ctx equal getContext 2D, this is the function that you use to get access to the canvas tags 2D drawing functions. . And make the canvas width is 778 and height is 625. The sprite width is 1038 and the sprite height is 883.

Next create an animate() function in the “script.js” file. In this function, we use the clearRect() to make inside the square empty. And use the drawImage() to draw the image into the square. The drawImage() needs 9 arguments, the first argument is the image you want to use which is “myImg”. The second and third arguments are the coordinate of the image where you want to start to clip. The fourth and fifth is the width and the height of the image you want to clip. The sixth and seventh is the coordinate where to place the image on the canvas. And the last two are the width and the height of the image to use. Next use the requestAnimationFrame() method to do an animation loop. And call the animate() function, the attacking cat image appears on the canvas.

Tags:

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *