簡體   English   中英

背景進度欄畫布

[英]Background Progress bar Canvas

我的問題是如何使用如下圖所示的畫布創建進度條的背景:

在此處輸入圖片說明

我已經為它編寫了代碼,但是我認為有一種更好的方法,例如,我想知道是否可以在一個畫布上執行此代碼:

 $(document).ready(function () { var canvasAnimation = document.getElementById("animation"); var ctxAnimation = canvasAnimation.getContext("2d"); ctxAnimation.beginPath(); ctxAnimation.arc(75, 75, 65, 0, 2 * Math.PI); ctxAnimation.lineWidth = 10; ctxAnimation.strokeStyle = "#F3F3F3"; ctxAnimation.stroke(); var canvasBackground = document.getElementById("background"); var ctxBackground = canvasAnimation.getContext("2d"); ctxBackground.beginPath(); ctxBackground.arc(75, 75, 65, 1.2, 2 * Math.PI); ctxBackground.lineWidth = 10; ctxBackground.strokeStyle = "#1ABC9C"; ctxBackground.stroke(); }) 
 .my-container{ position:relative; width:150px; height:150px; margin:50px auto; } canvas{ position:absolute; top:0; left:0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="my-container"> <canvas id="background" width="150" height="150"></canvas> <canvas id="animation" width="150" height="150"></canvas> </div> 

第二個問題:

第二個問題是我想使筆觸具有上圖所示的border-radius

使用單個畫布絕對可以做到這一點。 您只需要刪除第二個畫布及其上下文,並用ctxAnimation替換對ctxBackground的任何引用。 之所以可行,是因為Canvas API與SVG一樣,使用了畫家的渲染模型

在連續的操作中將油漆施加到輸出設備,以使每個操作都在輸出設備的某些區域上進行油漆。 當該區域與先前繪制的區域重疊時,新的油漆會部分或完全遮蓋舊的油漆。

在您的示例中,如果我們先繪制淺灰色的圓圈,然后再繪制青綠色線,則將青綠色線繪制在該圓上。 通過應用此技術,我們得到以下代碼:

const canvas = document.getElementById("animation");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(75, 75, 65, 0, 2 * Math.PI);
ctx.lineWidth = 10;
ctx.strokeStyle = "#F3F3F3";
ctx.stroke();

ctx.beginPath();
ctx.arc(75, 75, 65, 1.2, 2 * Math.PI);
ctx.lineWidth = 10;
ctx.strokeStyle = "#1ABC9C";
ctx.stroke();

至於啟用“邊界半徑”效果,可以將lineCap屬性設置為round: ctx.lineCap = "round";

這是最終代碼的小提琴。

您可能想在這里查看一些畫布文檔

Monica的答案很好,您也可以使用SVG的stroke-dashoffsetstroke-dasharray屬性來實現

查看此筆示例

這是用兩個SVG圓構建的,它們都沒有填充,它們只有筆觸,所以它們的中心是空白,底部的圓具有描邊顏色。

單擊填充按鈕時, .filled在頂部圓上添加.filled類,它使用覆蓋整個圓的破折號在筆畫中進行動畫處理,以更好地說明其工作原理, 請閱讀本文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM