Search code examples
javascripthtmlcanvascameraside-scroller

2D side scrolling camera view in html5


I was wondering how I could go about making a camera-like view where I could scroll a level within a canvas element just like this:

http://playbiolab.com/

Biolab screenshot


Solution

  • So you want a 500x500 canvas to display something (a game level) that is really 9000x500 or so.

    This is fine. What you do is think of the canvas as a "viewport" for a larger scene. You translate the canvas (or everything else) to the appropriate spot and draw all of the relevant things at that spot.

    Here's an example:

    http://jsfiddle.net/hKrrY/

    Click on the canvas and hold down your left arrow key to see the scene go by while the red player dot stays "still".

    As you scroll by the 100x100 canvas, you are seeing objects that are being drawn at once-offscreen locations like (330,50). Translating the canvas brings them into view.


    I guess its worth mentioning that this is where making optimizations in a canvas starts to really matter. The example I gave above is a very simplistic way to make a viewport, and as your code progresses you're going to want to think more and more about what it is you're drawing and how much you're drawing. You'll want to avoid drawing objects that are completely offscreen, for instance, and if your game or app has a background that is 9000x500 you probably don't want to be drawing the entire thing every time!

    So the concept is the takeaway here, but you'll want to think very hard about how you implement it and how much work you are making the canvas do. If you end up with performance problems in your side-scrolling app, be sure to let us know :)