<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>canvas画图</title>
<link rel="stylesheet" href="">
<style>
*{padding: 0; margin: 0; }
.circle{width: 300px;height: 300px;position: relative;}
canvas{display: block;margin: 0;position: absolute;background: white;left: 0;top: 0;}
#canvas_1{z-index: 2;position:absolute;left:72px;top:72px; }
#canvas_2{z-index: 3; background: transparent;transform:rotate(-90deg); position:absolute;left:72px;top:72px;}
#canvas_3{z-index:1}
.smallText{
font-size: 14px;
z-index: 4;
}
</style>
</head>
<body>
<div class="circle">
<canvas id="canvas_1" width="154" height="154"></canvas>
<span class="smallText">待解决</span>
<canvas id="canvas_2" width="154" height="154"></canvas>
<canvas id="canvas_3" width="300" height="300"></canvas>
</div>
<script>
function inte(percent){
//获取画布
var canvas_1 = document.getElementById("canvas_1");
var canvas_2 = document.getElementById("canvas_2");
var canvas_3 = document.getElementById("canvas_3");
//可以在画布上进行绘画,即返回一个对象,该对象可以在画布上进行操作,可以理解为画笔
var ctx_1 = canvas_1.getContext('2d');
var ctx_2 = canvas_2.getContext('2d');
var ctx_3 = canvas_3.getContext('2d');
//图像边框是10像素
ctx_1.lineWidth = 5;
ctx_1.strokeStyle = "#ccc";
//第一个圆的颜色为白色,为底部的白色圆圈
ctx_1.beginPath(); //画笔1的起始位置
//参数arc(x轴,y轴,半径,起始角(一般为0),结束角(一般为2*Math.PI),可选(false为顺时针,true为逆时针))
ctx_1.arc(canvas_1.width / 2, canvas_1.height / 2, canvas_1.width / 2 - ctx_1.lineWidth / 2, 0, Math.PI * 2, false);
//创建从当前点回到起始点的路径
ctx_1.closePath();
//绘制以上定义好的路线
ctx_1.stroke();
if (percent < 0 || percent > 100) {
throw new Error('percent must be between 0 and 100');
return
}
ctx_2.lineWidth = 5;
ctx_2.strokeStyle = "#f90";
var angle = 0;
var timer;
//定义一个自运行函数
(function draw(){
//requestAnimationFrame定义动画
timer = requestAnimationFrame(draw);
//clearRect清空给定矩形内的指定像素(参数:x轴,y轴,要清除矩形的宽度,要清除矩形的高度)
ctx_2.clearRect(0, 0, canvas_2.width, canvas_2.height)
//百分比圆环
ctx_2.beginPath(); //画笔2的起始位置
//创建部分圆或圆圈
ctx_2.arc(canvas_2.width / 2, canvas_2.height / 2, canvas_2.width / 2 - ctx_2.lineWidth / 2, 0, angle * Math.PI / 180, false);
angle++;
//取整
var percentAge = parseInt((angle / 360) * 100)
if (angle > (percent / 100 * 360)) {
percentAge = percent
window.cancelAnimationFrame(timer);
};
ctx_2.stroke();
ctx_2.closePath();
//保存当前环境状态
ctx_2.save();
ctx_2.beginPath();
//旋转当前的绘画
ctx_2.rotate(90 * Math.PI / 180)
ctx_2.font = '30px Arial';
ctx_2.fillStyle = 'red';
var text = percentAge + '%';
//fillText() 方法在画布上绘制填色的文本。文本的默认颜色是黑色。
//使用上面font 属性来定义字体和字号,并使用 fillStyle 属性以另一种颜色/渐变来渲染文本。
ctx_2.fillText(text, 55, -70);
ctx_2.closePath();
//返回之前保存过的路径状态和属性
ctx_2.restore();
ctx_3.lineWidth = 1;
ctx_3.strokeStyle = "#000";
ctx_3.beginPath();
ctx_3.arc(canvas_3.width / 2,canvas_3.height / 2,canvas_3.width / 2 -ctx_3.lineWidth / 2,0,Math.PI * 2,false);
ctx_3.closePath();
ctx_3.stroke();
})()
}
window.onload = inte(60);
</script>
</body>
</html>
里面有详细注释哦,下面是效果图: