**
js通过canvas来画图模拟进度条加载动画
**
html:
<div class="wai">
<div>模拟加载—>加载进度:<span id="num"></span></div>
<span id="dtnum"></span>
<canvas width="200" height="22" style="border-radius: 10px;" id="can">您的浏览器不支持canvas</canvas>
<br>
<button id="btnLogin">开始</button>
<button id="btnZt">暂停</button>
</div>
css:
.wai{
height: 80px;
width: 100%;
position: relative;
}
#dtnum{
position: absolute;
top: 23px;
z-index: 99999;
color: white;
font-size: 12px;
display: inline-block;
width: 40px;
}
#btnLogin{
width: 100px;
height: 30px;
font-size: 14px;
color: white;
background: #1568ff;
border: none;
border-radius: 15px;
cursor: pointer;
outline: none;
}
#btnZt{
width: 100px;
height: 30px;
font-size: 14px;
color: white;
background: #1568ff;
border: none;
border-radius: 15px;
cursor: pointer;
outline: none;
}
js:
(function(){
let canvas;
let ctx;
let num = document.getElementById('num');
let dtnum = document.getElementById('dtnum');
let btnLogin = document.getElementById('btnLogin');
let btnZt = document.getElementById('btnZt');
let setInt;
let k;
let bfb;
let col;
// 建立画布
canvas = document.getElementById('can');
ctx = canvas.getContext('2d');
//设置画布样式
canvas.width = 1024;
canvas.height = 20;
canvas.style.border = '1px solid #009688';
canvas.style.borderRadius = '10px';
// 初始值
k = 24;
bfb = 0;
col ='#009688';
// 开始
btnLogin.addEventListener('click',function () {
setInt = setInterval(function (a,b) {
jsq();
arc();
},1000);
});
// 暂停
btnZt.addEventListener('click',function () {
clearInterval(setInt);//清除计时器
});
//计时器运行函数
let jsq = function(){
let x = Math.ceil(Math.random()*40);//0-40之间的随机整数
k = k+x;
// console.log(k);
// 显示文字、样式
if(k>=1024){
clearInterval(setInt);
k = 1024;
col = '#ff0000';
bfb = (k-24)/10;
dtnum.style.left = k-24 + 'px';
num.innerText = bfb + '%';
dtnum.innerText = bfb + '%';
canvas.style.border = '1px solid #ff0000';
}else {
bfb = (k-24)/10;
dtnum.style.left = k-24 + 'px';
num.innerText = bfb + '%';
dtnum.innerText = bfb + '%';
}
};
//绘制进度条
let arc = function () {
ctx.strokeStyle = col;
ctx.lineWidth = 5;//画笔大小
ctx.beginPath();//开始作画
ctx.moveTo(0,0);//起始点
ctx.lineTo(0,20);
ctx.lineTo(k,20);
ctx.arc(k,10,10,Math.PI/2,-Math.PI/2,true);//画圆——默认逆时针false ,顺时针为true
ctx.lineTo(k,0);
ctx.lineTo(0,0);
ctx.closePath();//结束
ctx.stroke();//描边
ctx.fillStyle = col;
ctx.fill();
};
})();
效果演示: