1

I made this function based on the mozilla code snipppets. It wraps the native canvas2d methods and property setters and sends back this, the 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()...

My questions are two: is this faster than ctx.lineTo;ctx.moveTo if ctx is in your local function scope or even better this=ctx. Is there a better way to do this?

4

0 回答 0