查看環形圖效果javascript
主要用到幾個知識點css
一、lineCap:如何繪製每一條線段末端的屬性。有3個可能的值,分別是:butt(線段末端以方形結束), round (線段末端圓形結束)and square(線段末端以方形結束,可是增長了一個寬度和線段相同,高度是線段厚度一半的矩形區域)。默認值是 butt。 html
二、圓弧起始點與結束點的設置java
在本里中設置方式 ctx.arc(110, 110, 100, 0.75 * Math.PI, 0.75 * Math.PI + step * 1.5 * Math.PI, false); // false 是順時針canvas
三、LinearGradient的使用方法flex
完整的代碼以下 this
<div class="container"> <div class="progress_box"> <!-- 必定要設置width 和 height 不然圖形會變形 --> <canvas id="progress_bg" width="220" height="220"></canvas> <canvas id="progress_canvas" width="220" height="220"></canvas> <div class="progress_text" id="progress_text">正在加載中...</div> </div> </div>
<style> .progress_box { position: relative; width: 220px; height: 220px; display: flex; align-items: center; justify-content: center; background: #140c33; } #progress_bg { position: absolute; width: 220px; height: 220px; } #progress_canvas { width: 220px; height: 220px; z-index: 1; } .progress_text { position: absolute; display: flex; align-items: center; justify-content: center; color: #ddd; } .progress_info { font-size: 20px; padding-left: 16px; letter-spacing: 2px; } .progress_dot { width: 16px; height: 16px; border-radius: 50%; background: #fb9126 } </style>
<script> function drawProgressBg() { var canvas = document.getElementById("progress_bg"); var ctx = canvas.getContext("2d"); ctx.lineWidth = 4; ctx.strokeStyle = "#20183b"; ctx.lineCap = "round"; ctx.beginPath(); ctx.arc(110, 110, 100, 0, 2 * Math.PI, false); ctx.stroke(); } drawProgressBg() function drawCircle(step) { var canvas = document.getElementById("progress_canvas"); var ctx = canvas.getContext("2d"); var gradient = ctx.createLinearGradient(200, 100, 100, 200); gradient.addColorStop(0, "#2661DD"); gradient.addColorStop(0.5, "#40ED94"); gradient.addColorStop(1.0, "#5956CC"); ctx.lineWidth = 10; ctx.strokeStyle = gradient; ctx.lineCap = "round"; ctx.beginPath(); ctx.arc(110, 110, 100, 0.75 * Math.PI, 0.75 * Math.PI + step * 1.5 * Math.PI, false); // false 是順時針 ctx.stroke(); } //drawCircle() function countInterval() { var count = 0 var counterTimer = setInterval(function() { if (count <= 60) { this.drawCircle(count / 60) count += 2; } else { var text = document.getElementById("progress_text") text.innerHTML = "加載完成" clearInterval(counterTimer) } }, 100) } countInterval() </script>
注意:必定要設置 Canvas 的 width 和 height 不然圖形會變形。
spa