2013.08.28更新:

此次更新是修复上一次更新的遗留问题,即"有返回值的函数无法得到正确的返回值",比如getImageData,isPointInPath等,这个问题是因为为了实现链式语法,函数会总是返回this.其实要修复这个问题是很简单的,就是判断函数执行后是否有返回值,有的话就返回这个返回值,没有就继续返回this(大多数情况下都没有).

不过由于这个判断的原因,可能会对整体效率有那么一点点的影响;另外,在使用有返回值的函数后,后续就不能继续链式语法了.

另外我把原来的用来放函数名的数组变成了一个字符串,因为这样可以少写很多引号.

var XtendCanvas = function () {
    var pro = 'save,restore,scale,rotate,translate,transform,createLinearGradient,createRadialGradient,getLineDash,clearRect,fillRect,beginPath,closePath,moveTo,lineTo,quadraticCurveTo,bezierCurveTo,arcTo,rect,arc,fill,stroke,clip,clearShadow,fillText,strokeText,strokeRect,drawImage,drawImageFromRect,putImageData,createPattern,createImageData,textBaseLine,strokeStyle,lineWidth,globalAlpha,fillStyle,font,shadowOffsetX,shadowOffsetY,shadowBlur,shadowColor,lineCap,lineJoin,miterLimit,getImageData,isPointInPath'.split(',');
    function fn (canvas) {
        this.context = canvas.getContext('2d');
    }
    var old = document.createElement('CANVAS').getContext('2d');
    for(var i = 1,p=pro[0];p;p=pro[i++]) {
        // console.log(i +' >> '+ p + ' >> ' + typeof CanvasRenderingContext2D.prototype[p]);
        fn.prototype[p] = function  (p) { 
            return (typeof old[p] === 'function') ? function  () {
                    var r = this.context[p].apply(this.context,arguments);
                    return r === undefined ? this : r;
                } : function  () {
                    this.context[p] = Array.prototype.join.call(arguments);
                    return this;
                };
        }(p);
    }  
    return function  (canvas) {
        return new fn(canvas);
    };
    
}()
View Code

相关文章:

  • 2021-12-27
  • 2021-06-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-22
  • 2021-06-28
  • 2022-12-23
  • 2021-11-09
  • 2021-04-14
相关资源
相似解决方案