2011-10-29 4 views
2

그래서 항상 항상캔버스 체인 라이브러리 만들기

ctx.moveTo(x, y); 
ctx.lineTo(x1, y1); 
ctx.... 

캔버스 코드의 여러 줄을 쓸 때 게으르다. 대신 동적 인 방식이 아니더라도 모든 내용을 다룰 수있는 chainable 래퍼를 만들었습니다.

function CanvasChainer(ctx) { 
    this.ctx = ctx; 
} 

// just a small snippet 
CanvasChainer.prototype = { 
    beginPath: function() { 
    this.ctx.beginPath(); 
    return this; 
    }, 
    closePath: function() { 
    this.ctx.closePath(); 
    return this; 
    }, 
    fillText: function (str, x, y) { 
    this.ctx.fillText(str, x, y); 
    return this; 
    }, 
    moveTo: function (x, y) { 
    this.ctx.moveTo(x, y); 
    return this; 
    } 
} 

프로그래밍 방식으로 모든 것을 연결하려고하면 apply를 사용할 때이 오류가 계속 발생합니다. 또는

:

Illegal operation on WrappedNative prototype object 
this.ctx[i].apply(this.ctx[i], args); 

및 코드 :

var _canvas = document.createElement('canvas'), 
    SLICE = Array.prototype.slice, 
    _ctx; 

if (_canvas.attachEvent && window.G_vmlCanvasManager) { 
    G_vmlCanvasManager.initElement(_canvas); 
} 

_ctx = _canvas.getContext('2d'); 

function CanvasChainer(ctx) { 
    this.ctx = ctx; 
} 

CanvasChainer.prototype = { }; 

for (var p in _ctx) { 
    if (!CanvasChainer.prototype[p] && typeof _ctx[p] === 'function') { 
    (function (i) { 
     CanvasChainer.prototype[i] = function() { 
     if (arguments.length > 0) { 
      var args = SLICE.call(arguments, 0); 
      this.ctx[i].apply(this.ctx[i], args); 
     } 
     return this; 
     } 
    }(p)) 
    } 
} 

이 구현은 인수가 필요없는 경우에 작동합니다 (예 : ctx.beginPath()). 또한 사용 가능한 기능을 첨부하는 데만 신경 써야합니다.

+0

사용 레아 베루의 chainvas. http://leaverou.me/chainvas/ – Gerben

+0

고맙습니다. 나는 chainvas에 대해 좀 더 자세히 살펴 봐야 할 것이다. 그러나 kangax는이 특별한 문제에 대한 해결책을 발견했다. – hellatan

답변

2

HTMLRenderingContext의 컨텍스트에서 메소드를 호출하면 안됩니까?

은 교체 :

this.ctx[i].apply(this.ctx[i], args); 

로 :

this.ctx[i].apply(this.ctx, args); 
+0

아, 멋진 kangax를 잡아라! 그 모든 것을 렌더링하는 속임수. – hellatan

0

더 나은 코드 :

for (var p in _ctx) { 
    if (!CanvasChainer.prototype[p] && typeof _ctx[p] === 'function') { 
     CanvasChainer.prototype[p] = function (p) { 
     return function() { 
      return this.ctx[p].apply(this.ctx, arguments) || this; 
     }; 
     }(p); 
    } 
}