2012-07-10 69 views
2

我正在用Javascript制作一个游戏引擎,我想要一个可以旋转的相机对象。当相机旋转时,整个2D场景也会在相机的位置旋转。每个视觉实体也可以旋转,这是他们如何做到的:画布是否支持嵌套上下文保存?

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. 

我想以类似的方式实现相机旋转。基本上,前通过所有实体会和渲染他们,我这样做:

if (camera.rotation != 0) 
{ 
    renderer.context.save(); 
    renderer.context.rotate(camera.rotation); 
}  

//Loop through entities and render. 

然后,后实体已经完成(以及保存和恢复同样的背景下无数次),我想恢复上下文它的渲染,就像在此之前的状态:

if (camera.phi != 0) 
{ 
    renderer.context.restore(); 
}  

说我有2个实体这两者都是由某种程度的旋转,而且还旋转的摄像头,过程是这样的:

  1. 保存
  2. 保存
  3. 平移和旋转
  4. 从2
  5. 恢复保存
  6. 平移和旋转
  7. 从5
  8. 恢复恢复从1

是这种行为得到支持?我实施了它,它似乎工作,虽然有错误,所以我无法正确评估情况...

回答

3

这应该是适当的行为。请记住,在保存需要该功能的画布功能的上下文后,创建新的beginPath()调用,并在恢复之前在适当时关闭路径。

不妨看看这里:Understanding save() and restore()

我使用嵌套的情况下保存和在我的项目恢复。你只需要跟踪你在头脑中的位置。所以,如果你改变了一些东西,当你开始操纵你的下一次保存时,你将会处于这种转变之中。

+0

是的,“嵌套”概念是堆栈行为。在OP的示例中,堆栈变为空 - > 1 - > 1 2 - > 1 - > 1 - > 1 - >空。 – pimvdb 2012-07-10 21:33:01