我基于mozilla代码snipppets创建了这个函数。它包装了本机canvas2d方法和属性设置器,并将它发送回context2:
// f() thisCanvas, Richard Maloney 2013
function thisCanvas()
{ var methods = ['arc','arcTo','beginPath','bezierCurveTo','clearRect','clip',
'closePath','drawImage','fill','fillRect','fillText','lineTo','moveTo',
'quadraticCurveTo','rect','restore','rotate','save','scale','setTransform',
'stroke','strokeRect','strokeText','transform','translate'];
for (var i = 0, len = methods.length; i < len; i++)
{ var m = methods[i];
CanvasRenderingContext2D.prototype["_"+m] = (function (m) {
return function () {
this[m].apply(this, arguments);
return this;
};}(m));
}
var props = ['canvas','fillStyle','font','globalAlpha','globalCompositeOperation',
'lineCap','lineJoin','lineWidth','miterLimit','shadowOffsetX','shadowOffsetY',
'shadowBlur','shadowColor','strokeStyle','textAlign','textBaseline'];
for (i = 0, len = props.length; i < len; i++)
{ var p = props[i];
CanvasRenderingContext2D.prototype["_"+p] = (function (p) {
return function (value){
this[p]= value;
return this;
};}(p));
}
}
thisCanvas();
//usage: ctx._moveTo(x,y)._lineTo(x,y)._closePath()...
我的问题是两个:这比ctx.lineTo更快; ctx.moveTo如果ctx在你的本地函数范围内,或者甚至更好这个= ctx。有更好的方法吗?