I'm making a game engine in Javascript, and I want to have a camera object, which can be rotated. When the camera is rotated, the whole 2D scene is rendered rotated too, around the camera's position. Each of the visual entities can be rotated as well, and this is how they do it:
context.save(); //As we are about to change the context's state, we need to save it so it can be restored.
context.translate(entity.position.x + entity.width/2, entity.position.y + entity.height/2); //Translate to the center of the entity so the context can be rotated with the desired effect.
context.rotate(entity.rotation); //In radii.
context.drawImage(entitiy.image, -entity.width/2, -entity.height/2);
context.restore(); //Restore the previous context state so it can be used later by other entities.
I would like to achieve camera rotation in a similar way. Basically, before going through all entities and rendering them, I would do this:
if (camera.rotation != 0)
{
renderer.context.save();
renderer.context.rotate(camera.rotation);
}
//Loop through entities and render.
And then, after the entities have finished (and saved and restored the same context numerous times), I would like to restore the context to it's state before rendering, like this:
if (camera.phi != 0)
{
renderer.context.restore();
}
Say I have 2 entities which are both rotated by some degree, and a camera that is also rotated, the process would look like this:
Is this type of behavior supported? I implemented it, and it seems to be working, although there are bugs so I am unable to assess the situation properly...
This should be appropriate behavior. Remember to create new beginPath() calls after saving the context for the canvas features that require that, and to closePath when appropriate before restoring.
Might look here: Understanding save() and restore()
I use nested context saves and restores in my projects. You just have to keep track of where you are in the stack in your head. So if you transform something, you're going to be at that transform when you start manipulating your next save, etc.
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