I'm building a side scrolling platformer with Javascript and the canvas element for a school project. I have the character all sorted out. He runs left and right, and has a different sprite set for standing still. The game has gravity, and I can jump. Now what I can't get my head around is how to implement side scrolling.

The game world will be tile based. Each tile will be 20x20 pixels. When the character gets to the edge of the screen, it should scroll with the character to explore the level further.

Can anyone point me in the right direction to a resource that explains how to programmatically do this? Language specific to Javascript would be good, but anything would be a help.

  • 1
    \$\begingroup\$ I think this answer does a fairly good job of explaining the basics of scolling. \$\endgroup\$
    – thedaian
    Oct 27, 2011 at 19:05

1 Answer 1


Pulled from some of last year's code, I was prototyping a top down scroller in JS/Canvas. The principles the same, you translate your canvas by some value representing your offset from the world origin, and then draw images to it, and lastly restore the canvas's transform state to what it was originally.

this.context = this.canvas.getContext('2d');
context.save(); //save the existing canvas transform state (identity matrix)
context.translate(x, y);
context.translate(-(sprite.width/2), -(sprite.height/2)); //centring
context.drawImage(image, 0 ,0);

//remove the just-created transforms so you're back to working with an identity 
//matrix -- or whatever matrix you had in place before .save() -- they're nestable.

(The context acts like a stack to store to the transformations -- which is really just a multiplication of matrices where if you save the state of the master matrix, and multiply further matrices into it, you can remove them by restoring the saved state. Undo function for matrices.)

I remember that there were some issues for me with ordering, i.e. generally you will translate a sprite to centre it first, then rotate it, then position it in screen space, however as you can see above the order from my working code was actually the reverse order. Just a heads up so you know you'll probably have to fiddle this a bit to get it right.

PS. I can't recall whether drawImage() accepts negative coordinates, but if so you should be able specify your sprite centring there and remove the second call to translate().

  • \$\begingroup\$ Hi! I dont get how you implement side scrolling with this technique. I understand that it kind of "translate" sprites position, but the background itself doesnt move. Am I missing something? \$\endgroup\$ Aug 19, 2013 at 15:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .