Javascript 创建画布链库
所以我越来越懒了,总是写出来Javascript 创建画布链库,javascript,canvas,Javascript,Canvas,所以我越来越懒了,总是写出来 ctx.moveTo(x, y); ctx.lineTo(x1, y1); ctx.... 用于多行画布代码。取而代之的是,我创建了一个可链接的包装器来处理所有这些内容,尽管不是以一种动态的方式: function CanvasChainer(ctx) { this.ctx = ctx; } // just a small snippet CanvasChainer.prototype = { beginPath: function () {
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;
}
}
当我尝试以编程方式附加所有内容时,当我尝试使用apply
或call
时,我会不断出现此错误:
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
的上下文中调用方法吗
替换:
this.ctx[i].apply(this.ctx[i], 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);
}
}
使用Lea Verou的chainvas。谢谢你,格本。我必须更深入地了解chainvas,但是kangax找到了解决这个特殊问题的方法啊,抓到kangax真棒!这就是渲染一切的诀窍。
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);
}
}