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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With