2012-09-09 3 views
2

저는이 가짜 캔버스를 모든 라인, 커브 및 moveTo의 사후 처리를위한 임의의 프레임 워크로 넘기려는 의도로 캔버스를 "가짜"로 만들려고합니다.캔버스 위조 -이 기능을 사용할 수 있습니까?

이 코드를 관리하려면 실제로이 코드를 사용해 보았습니다.하지만이 행운의 장면에서 얼마나 많은 행운이 있었는지 알고 싶습니다.

(function(){ 
    function DebugCanvas(){ 
     this._dom = document.createElement('canvas'); 
     addPropertiesToObject.call(this, this._dom); 
     this._fakeContext = null; 
    } 

    Object.defineProperties(DebugCanvas.prototype, 
    { 
     'constructor' : { 
      'value' : DebugCanvas, 
      'enumerable' : true 
     }, 

     'getContext' : { 
      'value' : function(which){ 
       var ctx; 
       if(which == '2d'){ 
        if(this._fakeContext == null){ 
         this._fakeContext = new FakeContext(this._dom); 
        } 
        ctx = this._fakeContext; 
       } else { 
        ctx = this._dom.getContext(which); 
       } 
       return ctx; 
      }, 
      'enumerable' : true 
     } 
    } 
); 

function FakeContext(debugCanvas){ 
    this._debugCanvas = debugCanvas; 
    this._realContext = debugCanvas._dom.getContext('2d'); 
    addPropertiesToObject.call(this, this._realContext); 
} 

Object.defineProperties(FakeContext.prototype, { 
    'toString' : { 
     'value' : function(){ 
      return '[Object FakeContext]'; 
     }, 
     'enumerable' : true 
    }, 

    'canvas' : { 
     'get' : function(){ 
      return this._debugCanvas; 
     }, 
     'set' : function(c){ return }, 
     'enumerable' : true 
    } 
}); 

function addPropertiesToObject(from){ 
    var description, obj; 

    for(var prop in from){ 
     obj = from; 
     do { 
      if(obj.hasOwnProperty(prop) && 
       !this.constructor.prototype.hasOwnProperty(prop)){ 

       try{ 
        description = Object.getOwnPropertyDescriptor(obj, prop); 
        Object.defineProperty(this.constructor.prototype, prop, description); 
       } catch(err){ 
        this[ prop ] = from[ prop ]; 
       } 
       break; 
      } 
     } while(obj = Object.getPrototypeOf(obj)); 
    } 
}; 
})() 

기본적인 아이디어는 멀리있는 그대로 캔버스 (모든 체인 위쪽), 컨텍스트 '와 context.prototypes'가짜 객체의 프로토 타입 속성 ', canvas.prototypes'을 모두 복사하는 것입니다 아직 거기에 존재하지 않습니다.

+0

실제 캔버스를 사용할 때의 문제점은 무엇입니까? – Kristian

+0

»포스트 프로세스 모든 그리기 명령«, 그 이유입니다. – philipp

답변

2

자바 스크립트에서는 원본과 동일한 속성/방법으로 대체 개체를 자유롭게 구성 할 수 있으며 원본 대신 사용할 수 있습니다. 메서드 호출 또는 속성 액세스는 어느 쪽이든 같고 호출 코드는 일반적으로 차이를 알 수 없습니다. 이것은 자바 스크립트에서 때때로 할 매우 유용한 일이 될 수 있습니다.

이렇게 복잡한 대체 부분은 모든 메서드와 속성의 실제 동작을 에뮬레이트하여 원하는 코드를 전달하는 코드입니다. 그러나 성공적으로 수행 할 수 있다면 정상적으로 작동합니다. 행운은 관련이 없습니다 - 메서드/속성의 에뮬레이션이 옳다면이 기능이 작동해야합니다.

+0

실제로 설정 한 테스트 환경에서 작동합니다. 나는 에뮬레이션 할 수없는 행동에 대해 확신 할 수 없다 ... – philipp

+0

@philipp - 그것은 어려운 부분이다. 가짜 객체를 전달하는 코드가 그 객체로 전달하려고 시도하는 코드와 예상되는 결과에 전적으로 의존합니다. – jfriend00

+0

은 컨텍스트의 모든 콜백을 오버라이드하므로 좌표를 넘길 수 있습니다. 여기서는 의도에 대해 설명합니다. http://gamedev.stackexchange.com/questions/14323/scrolling-box2d-debugdraw 다음으로 처리 할 수있는 다른 프레임 워크에는 매우 유용 할 수 있습니다. – philipp

관련 문제