Canvas的方法覆盖和实现新的API

 有时候为了特定需求或者特殊目的,需要覆盖或者重写某个API,在Canvas中,就需要用到CanvasRenderingContext2D这个对象。

CanvasRenderingContext2D为Canvas 提供了丰富的2d绘制函数,当我们需要重写Canvas API的时候,就需要重写这里的方法,下面就以一个例子为证:

  需求:

         为Canvas实现绘制虚线的API:dashedLineTo,这个API的用法类似lineTo,但是使用之前都必须知道上一次绘制的点。这里就需要用一个对象来保存上次moveTo的 点,所以要重写moveTo的API和实现dashedLineToAPI

 

  

  var   moveToFunction = CanvasRenderingContext2D.prototype.moveTo;//保存原生moveTo的引用

CanvasRenderingContext2D.prototype.lastMoveToLocation = {};//保存上一次moveTo的点

CanvasRenderingContext2D.prototype.moveTo = function (x, y) {
   moveToFunction.apply(context, [x,y]);
   this.lastMoveToLocation.x = x;
   this.lastMoveToLocation.y = y;
};

CanvasRenderingContext2D.prototype.dashedLineTo = function (x, y, dashLength) {
   dashLength = dashLength === undefined ? 5 : dashLength;

   var startX = this.lastMoveToLocation.x;
   var startY = this.lastMoveToLocation.y;

   var deltaX = x - startX;
   var deltaY = y - startY;
   var numDashes = Math.floor(Math.sqrt(deltaX * deltaX + deltaY * deltaY) / dashLength);

   for (var i=0; i < numDashes; ++i) {
      this[ i % 2 === 0 ? 'moveTo' : 'lineTo' ]
         (startX + (deltaX / numDashes) * i, startY + (deltaY / numDashes) * i);
   }

   this.moveTo(x, y);
};

 

 

使用的时候直接在context上操作就行了

var context = document.getElementById('canvas').getContext('2d');
context.lineWidth = 3;
context.strokeStyle = 'blue';

context.moveTo(20, 20);
context.dashedLineTo(context.canvas.width-20, 20);
context.dashedLineTo(context.canvas.width-20, context.canvas.height-20);
context.dashedLineTo(20, context.canvas.height-20);
context.dashedLineTo(20, 20);
context.dashedLineTo(context.canvas.width-20, context.canvas.height-20);
context.stroke();

 

posted @ 2015-04-27 15:03  liuminghai  阅读(760)  评论(0编辑  收藏  举报