向原型中添加绘制方法

绘制圆点线

在 Canvas 中没有直接绘制圆点(dotted)线的 API,需要的时候可以自行扩展 CanvasRenderingContext2D 原型,进行绘制圆点线。

let canvasPrototype = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
canvasPrototype.dottedLine = function (x1, y1, x2, y2, interval) {
  if (!interval) {
    interval = 5;
  }
  let isHorizontal = true;
  if (x1 == x2) {
    isHorizontal = false;
  }
  let len = isHorizontal ? x2 - x1 : y2 - y1;
  this.moveTo(x1, y1);
  let progress = 0;
  while (len > progress) {
    progress += interval;
    if (progress > len) {
      progress = len;
    } if (isHorizontal) {
      this.moveTo(x1 + progress, y1);
      this.arc(x1 + progress, y1, 1, 0, Math.PI * 2, true);
      this.fill();
    } else {
      this.moveTo(x1, y1 + progress);
      this.arc(x1, y1 + progress, 1, 0, Math.PI * 2, true);
      this.fill();
    }
  }
}

调用:

// 默认绘制圆点线
context.dottedLine(10, 100, 200, 200);
// 指定圆点间距
context.dottedLine(10, 100, 200, 200, 10);

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress