You can accomplish this with CanvasRenderingContext2D
's methods setTransform
, save
, and restore
. Together they allow you to create a draw transform stack, which permits you to draw all your tiles at their (unchanging) world position, but have them move around on screen.
If you have a position of the left-top world-position of your viewport, you can create a simple camera object:
var camera = {x: xPosition, y: yPosition};
Then you can update only that value and use it to offset your view by setting an initial base-transform. (Pay attention to argument order, as they comprise a 2x2 matrix followed by a 2d translation vector):
context.setTransform(
1, 0,
0, 1,
-1 * camera.x,
-1 * camera.y);
Then when you draw individual objects, you can add another transform, draw the image, and then pop that transform back off the stack:
var tile = {pos: {x: xPosition, y:yPosition}, img: tileImage };
context.save();
context.translate(tile.pos.x, tile.pos.y);
context.drawImage(tile.img, 0, 0);
context.restore();
Adding zoom and rotation can be accomplished with the same technique, but they require more terms in the transform. Clamping the motion of the camera, as well as picking items in screenspace, are more complicated. But those would all be separate topics.