html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圆环图封装</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
js代码如下
<script src="jrChart.js"></script>
<script>
var obj = {
id:"container",
width:1000,
height:500,
data:[
{
num:63,
color:"yellow",
angle:60
}
],
circleX:250,
circleY:250,
radius:100,//半径
startType:4,
fontColor:"red",
bottomColor:"red"
};
drawCirque(obj);
</script>
引入名叫jrChart的js文件
function drawCirque(obj) {
var width = obj.width;
var height = obj.height;
var id = obj.id;
var data = obj.data;
var circleX = obj.circleX;
var circleY = obj.circleY;
var radius = obj.radius;
var startType = obj.startType;
var fontColor = obj.fontColor;
var bottomColor = obj.bottomColor;
var container = document.getElementById(id);
container.style.width = width + "px";
container.style.height = height + "px";
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.style.border = "1px solid red";
var cvs = canvas.getContext("2d");
container.appendChild(canvas);
var interval;
var start;
var end = 0;
var increment = 2 * Math.PI / 100;
var i = 0;
if (startType === 1) {
start = -0.5 * Math.PI;
interval = setInterval(function () {
i++;
end = start + increment * i;
cvs.clearRect(0, 0, 1000, 500);
cvs.beginPath();
cvs.strokeStyle = bottomColor;
cvs.lineWidth = 10;
cvs.lineCap = "round";
cvs.arc(circleX, circleY, radius, 0, Math.PI * 2);
cvs.closePath();
cvs.stroke();
//
cvs.strokeStyle = data[0].color;
cvs.beginPath();
cvs.arc(circleX, circleY, radius, start, end);
cvs.stroke();
var text = i + "%";
cvs.font = "30px 宋体";
cvs.fillStyle = fontColor;
cvs.fillText(text, 230, 240);
if (end >= data[0].num * increment - 0.5 * Math.PI) {
clearInterval(interval);
}
}, 10);
} else if (startType === 2) {
interval = setInterval(function () {
start = 0;
i++;
end = start + increment * i;
cvs.clearRect(0, 0, 1000, 500);
cvs.beginPath();
cvs.strokeStyle = bottomColor;
cvs.lineWidth = 10;
cvs.arc(circleX, circleY, radius, 0, Math.PI * 2);
cvs.closePath();
cvs.stroke();
//
cvs.strokeStyle = data[0].color;
cvs.beginPath();
cvs.arc(circleX, circleY, radius, start, end);
cvs.stroke();
var text = i + "%";
cvs.font = "30px 宋体";
cvs.fillStyle = fontColor;
cvs.fillText(text, 230, 240);
if (end >= data[0].num * increment ) {
clearInterval(interval);
}
}, 10);
}
else if (startType === 3) {
start = 0.5 * Math.PI;
interval = setInterval(function () {
i++;
end = start + increment * i;
cvs.clearRect(0, 0, 1000, 500);
cvs.beginPath();
cvs.strokeStyle = bottomColor;
cvs.lineWidth = 10;
cvs.arc(circleX, circleY, radius, 0, Math.PI * 2);
cvs.closePath();
cvs.stroke();
cvs.strokeStyle = data[0].color;
cvs.beginPath();
cvs.arc(circleX, circleY, radius, start, end);
cvs.stroke();
var text = i + "%";
cvs.font = "30px 宋体";
cvs.fillStyle = fontColor;
cvs.fillText(text, 230, 240);
if (end >= data[0].num * increment + 0.5 * Math.PI) {
clearInterval(interval);
}
}, 10);
结果如下
注:插件是有过渡动画效果的