canvas繪制虛線,虛線方框,虛線圓

canvas沒有提供繪制虛線的api,我們可以通過moveTo,和lineTo來實現(xiàn)繪制虛線的需求。
思路是將一整條虛線分成若干個小線段,遍歷這些小線段,單數(shù)線段通過lineTo繪制,雙數(shù)線段使用moveTo跳過
具體實現(xiàn)方法如下

const drawDashLine = ([x1, y1], [x2, y2], step = 5) => {
    const x = x2 - x1,
        y = y2 - y1,
        count = Math.floor(Math.sqrt(x * x + y * y) / step),
        xv = x / count,
        yv = y / count;
    ctx.beginPath();
    for (let i = 0; i < count; i ++) {
        if (i % 2 === 0) {
            ctx.moveTo(x1, y1);
        } else {
            ctx.lineTo(x1, y1);
        }
      x1 += xv;
      y1 += yv;
    }
    ctx.lineTo(x2, y2);
}

在線示例

有了繪制虛線的方發(fā),我們便可以輕易的繪制出虛線方框

const drawDashRect = (left, top, width, height, step = 5) => {
    drawDashLine([left, top], [left + width, top], step);
    ctx.stroke();
    drawDashLine([left + width, top], [left + width, top + height], step);
    ctx.stroke();
    drawDashLine([left + width, top + height], [left, top + height], step);
    ctx.stroke();
    drawDashLine([left, top + height], [left, top], step);
    ctx.stroke();
}

我們知道arc方法不止可以繪制圓,還可以繪制圓弧,所以我們可以繪制多個小圓弧,組成一個虛線圓

const drawDashRound = (x, y, radius, step = 5) => {
    const count = Math.floor(360 / step);
    step = 5 / 180 * Math.PI * 2;
    for (let b = 0, e = step / 2; e <= 360; b += step, e += step) {
      ctx.beginPath()
      ctx.arc(x, y, radius, b, e);
      ctx.stroke();
    }
}

在線示例

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 書中代碼示例效果展示:Core HTML5 Canvas Examples 基礎(chǔ)知識 canvas元素 canva...
    szu_bee閱讀 3,052評論 2 28
  • 使用canvas 繪制圖形 上一篇 canvas基本用法在學(xué)習(xí)了canvas基本用法 我們開始著手在 canvas...
    閑不住的李先森閱讀 1,155評論 0 0
  • UIBezierPath Class Reference 譯:UIBezierPath類封裝了Core Graph...
    鋼鉄俠閱讀 1,945評論 0 3
  • 一:canvas簡介 1.1什么是canvas? ①:canvas是HTML5提供的一種新標(biāo)簽 ②:HTML5 ...
    GreenHand1閱讀 4,882評論 2 32
  • 他叼著煙打開門的時候,意外地發(fā)現(xiàn)電梯口坐了一個人。那個人聽見聲響,抬起頭來朝他看了一眼,嘴唇動了動又合上了。他倚在...
    成碟青瓜過大海閱讀 651評論 0 1

友情鏈接更多精彩內(nèi)容