回覆列表
  • 1 # 使用者6354108401155

    繪製圓點線

    查了一下,在Canvas中沒有直接繪製圓點(dotted)線的API。也就是說,如果要繪製這樣的線段(路徑)需要特殊處理。也就是說,需要透過JavaScript另外封裝一個API。比如封裝一個CanvasRenderingContext2D.dottedLine,然後透過context.dottedLine繪製。接下來,看看如何封裝這個API:

    var canvasPrototype = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;

    canvasPrototype.dottedLine = function (x1,y1, x2, y2, interval) {

    if (!interval) {

    interval = 5;

    }

    var isHorizontal = true;

    if (x1 == x2) {

    isHorizontal = false;

    }

    var len = isHorizontal ? x2 - x1 : y2 - y1;

    this.moveTo(x1, y1);

    var 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();

    }

    }

    }

    在Canvas畫布中,透過下面的方式就可以繪製圓點線:

    context.dottedLine(10, 100, 200, 200);

    當x1和x2的值相等時,可以繪製豎線:

    context.dottedLine(10, 100, 10, 200);

    同時我們也可以改變間距值:

    context.dottedLine(10, 100, 200, 200, 10);

    使用類似的方法,我們就可以繪製一個圓點線的距形:

    context.dottedLine(10, 100, 200, 200, 10);

    context.dottedLine(10, 100, 10, 200, 10);

    context.dottedLine(200, 100, 200, 200, 10);

  • 中秋節和大豐收的關聯?
  • 茶梅冬天能移栽嗎?怎麼移栽?