# Can I use a translate function to implement a viewport?

I read this great question and its accompanying great answer about rendering a viewport in a top down 2D game:

As for actually drawing the objects the camera can "see", you now draw all objects relative to the camera's world coordinates. To compute an object's screen position relative to the camera, simply do:

``````int screenX, screenY; //screen position of the object being drawn

screenX = object.x-camera.x;
screenY = object.y-camera.y;
``````

After thinking about this, it would be really invasive to change every place I render to run this `object.coord - camera.coord` equation first.

I'm wondering if this could be accomplished in one non-invasive step that translates the coordinate system first. I'm rendering on the html5 canvas and this translate function says:

Moves the origin point of the context to (x, y).

I'm having trouble visualizing this though. Does this mean I simply plug `(-camera.x, -camera.y)` into the function? Should I use a translate function to render a viewport or is there a good reason to apply the equation on every thing I render?

-

Yes you can, that's what I'd do.

Each frame you need to reset the transformation by calling ctx.setTransform with an identity matrix. Then you need to do whatever transformations you want (e.g. translate).

Note that you'll still need to do culling unless you want to draw every item in the universe on each frame.

-

The equations you've quoted are translations. A single `translate()` to move the entire viewport is may appear as a more efficient one-step solution, but it performs the same calculations for every object to be drawn. The algorithm required for moving a 2D camera is so straightforward, there are no real shortcuts or detours at play. Every sensible method will function and perform similarly.

-

logically speaking, even if you use a translate function, at the bottom line, it does calculate the equation whenever you use the function. In my experience with Unity3D, I can simply switch between world-position and local-position. Under the hood, they are implementing the equations anyway. Its always nice to have separate functions for translating in context of world model or local model. IMHO, I would recommend against using direct hard codded implementations.

-