<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style type="text/css">
* { margin: 0; padding: 0; }
.content { width: 200px; height: 200px; margin: 100px auto 0; }
</style>
</head>
<body>
<div class="content">
<canvas class="canvas" id="canvas" width="200" height="200"></canvas>
</div>
<script src="count.js"></script>
</body>
</html>
var srcDegree = 0, //初始位置角度
targetDegree = 360, //结束位置角度
allTime = 10,//总时间
valueTime = 10, //默认动态时间 = 总时间
drawTimeTxt = 10, //绘制时间 = 默认动态时间
size = 200,//canvas 大小
borderWidth = 10,//线条宽度
baseLineColor = '#ddd',//默认圆颜色
valueLineColor = '#176ee7',//动态圆颜色
font = '60px Arial', //字体
fontColor = '#176ee7',//字体颜色
timer;//计时器
var canvas = document.getElementById('canvas'); //获取id
var ctx = canvas.getContext('2d'); //创建对象
//绘制基础圆
function drawBase(){
ctx.beginPath();//开始路径
ctx.lineWidth = borderWidth;//线条宽度
ctx.strokeStyle = baseLineColor; //设置笔触颜色
ctx.arc(size/2,size/2,(size-borderWidth)/2,0,2*Math.PI,false);//ctx.arc(x, y, r, start, end, false); x,y为圆的圆心坐标,start为开始角度(弧度),end为结束角度(弧度),false是设置绘制圆以顺时针方向
ctx.stroke();//绘制完成
}
//绘制动态圆
function drawValue(srcDegree,targetDegree){
ctx.beginPath();
ctx.lineWidth = borderWidth;
ctx.strokeStyle = valueLineColor;
ctx.arc(size/2,size/2,(size-borderWidth)/2,degreeToRadian(srcDegree-90),degreeToRadian(targetDegree-90),false);
ctx.stroke();
}
//处理角度
function degreeToRadian(degree){
return degree * Math.PI / 180;
}
//绘制文字
function textTime(){
ctx.font = font;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = fontColor;
ctx.fillText(drawTimeTxt,size/2,size/2);
}
//清除画布
function clearAll(){
ctx.clearRect(0,0,size,size);
}
//进度条
function draw(srcDegree,targetDegree){
clearAll();
textTime();
drawBase();
drawValue(srcDegree,targetDegree);
}
//进度条动画
function drawFrame(){
var easing = 360 / allTime /100 ; // 圆环角度/时间
if(Math.round(srcDegree)>360){
clearInterval(timer);
// clearAll();
}else{
draw(Math.round(srcDegree),targetDegree);
srcDegree += easing;
valueTime = valueTime - 0.01;
drawTimeTxt = Math.ceil(valueTime);
}
}
//执行倒计时
function render(){
timer = setInterval(drawFrame, 10);
}
render();