2012-07-10 68 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