Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving the "camera" of an HTML Canvas element

I'm trying to find a clean way to "move the camera" of a canvas element.

This for my prototype game (side scroller). I'd love to think there's a better solution than moving the whole set of nodes to simulate a "camera" moving around.

Am almost certain to have read a simple how-to (using offsets?) but the fact I don't find anything like that starts to raise doubts... have I imagined reading that!?

Thanks to help me clarify... J

like image 314
Jem Avatar asked Dec 27 '22 10:12

Jem


1 Answers

Presumably you redraw your whole game scene 30 times a second (more or less)

You need to redraw your whole game scene but first translate the Canvas context by some offset.

context.translate(x,y) is precisely what you want. You'll want to read up on the use of that as well as the save() and restore() methods.

When you translate the context, everything drawn afterwards is shifted by that amount.

So you constantly draw something (maybe an enemy) at 50,50 using drawImage(badguy,50,50). Then the player moves, which changes the x of translate to -1 (because the player is moving to the right) instead of 0. You still draw the enemy sprite with the command drawImage(badguy,50,50), but when you draw it the enemy shows up as if it were at 49,50 because of the context.translate(-1,0) command shifting everything before its drawn.

Of course when you get into performance you'll want to be making sure that you are only ever drawing things that can actually be seen on the screen! If your are far down the level with context.translate(-2000,0), you dont want to be drawing objects at 50,50 anymore, only ones that intersect the viewable area.

like image 98
Simon Sarris Avatar answered Jan 15 '23 03:01

Simon Sarris