主要用到几个知识点
1、lineCap:如何绘制每一条线段末端的属性。有3个可能的值,分别是:butt(线段末端以方形结束), round (线段末端圆形结束)and square(线段末端以方形结束,但是增加了一个宽度和线段相同,高度是线段厚度一半的矩形区域)。默认值是 butt。
2、圆弧起始点与结束点的设置
在本里中设置方式 ctx.arc(110, 110, 100, 0.75 * Math.PI, 0.75 * Math.PI + step * 1.5 * Math.PI, false); // false 是顺时针
3、LinearGradient的使用方法
完整的代码如下
<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 否则图形会变形。