创建一个canvas链库



我真的很懒,总是写

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

表示多行画布代码。相反,我创建了一个可链包装器来处理所有这些东西,尽管不是那么动态:

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;
  }
}

当我尝试以编程方式附加所有内容时,当我尝试使用applycall时,我一直得到此错误:

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())。我也只关心附加可用的函数。

不应该在HTMLRenderingContext上下文中调用method吗?

替换:

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

:

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

更好的代码:

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);
   }
 }

最新更新