Rendering Sprite Sheet in Canvas

A couple of months back I wanted to live stream some code. I ended up starting a breakout clone in Html5 / Canvas / Js - but never got past figuring out the basics of how to render items from a spritesheet into a canvas as seperate sprites and some animation stuff before my life as a parent got in the way. I will not be live streaming anything in the near future - and the code has not moved forward in four months, but I thought that the code should serve as a lesson somehow.

The entry point of the application is just some setup code, and then an infinite loop to render the sprites to screen.

  • The first parts imports CanvasContext, Sprite and Sprites (see below).

  • The next part sets up a canvas context and makes an array of sprites

  • First sprite gets a ticksPerFrame value set (for animation purposes)

  • Then each sprite loads its image(s)

  • Finally the loop clears the screen, renders each sprite, and runs again

The CanvasContext module is pretty boring - so I will not go through it here.

The Sprites module is just a list of simple subclasses of the Sprite class - go see it here, if you are curious.

The real interesting part is the Sprite class - which inherits from ImageShape. ImageShape can load a remote image and draw it to a canvas.

A sprite object is more or less the same thing. However it can be render only a section of larger image, which means that the same image file can be used for multiple sprites. Then you only need to load the image once.

The largest part of the sprite class is the constructor, which just sets a lot of instance variables, and a setter for setting the ticksPerFrame (which defaults to 10).

The step method allows the class to step through multiple sub images - each sub image only changes after a set amount of milliseconds (ticks from above).

The render method calculates where in the larger image the current animation frame is - and then renders that to the canvas with the drawImage call.

See the all the code on github