溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何實現(xiàn)HTML5 Canvas繪制圓點虛線

發(fā)布時間:2021-09-28 14:54:32 來源:億速云 閱讀:163 作者:iii 欄目:web開發(fā)

這篇文章主要介紹“如何實現(xiàn)HTML5 Canvas繪制圓點虛線”,在日常操作中,相信很多人在如何實現(xiàn)HTML5 Canvas繪制圓點虛線問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何實現(xiàn)HTML5 Canvas繪制圓點虛線”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

HTML5 Canvas 提供了很多圖形繪制的函數(shù),但是很可惜,Canvas API只提供了畫實線的函數(shù)(lineTo),卻并未提供畫虛線的方法。這樣的設(shè)計有時會帶來很大的不便,《JavaScript權(quán)威指南》的作者David Flanagan就認為這樣的決定是有問題的,尤其是在標準的修改和實現(xiàn)都比較簡單的情況下 (“…something that is so trivial to add to the specification and so trivial to implement… I really think you’re making a mistake here” — http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2007-May/011224.html)。

在Stack Overflow上,Phrogz提供了一個自己的畫虛線的實現(xiàn)(http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas),嚴格的說,這是一個點劃線的實現(xiàn)(p.s. 我認為該頁面上Rod MacDougall的簡化版更好)。那么,如果需要畫圓點虛線(如下圖所示),應該怎么辦呢?

如何實現(xiàn)HTML5 Canvas繪制圓點虛線

以下是我自己的實現(xiàn),只支持畫水平的和垂直的圓點虛線,可以參考Phrogz與Rod MacDougall的方法來添加斜線描畫的功能。

代碼如下:

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,2*Math.PI,true);
           this.fill();
       } else {
           this.moveTo(x1,y1+progress);
           this.arc(x1,y1+progress,1,0,2*Math.PI,true);
           this.fill();
       }
   }
}

到此,關(guān)于“如何實現(xiàn)HTML5 Canvas繪制圓點虛線”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI