settimeoutCode
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas绘制饼图</title>
<script>
/**
* 绘制饼图
* @param {array} data_arr 扇形比例的数组
* @param {array} color_arr 每个扇形的颜色数组
*/
function drawCircle(data_arr, color_arr) {
var canvas = document.getElementById('canvas_circle');
var ctx = canvas.getContext('2d');
var radius = canvas.height / 2 - 20; //半径
var ox = radius + 20,
oy = radius + 20; //圆心
var startAngle = 0; //起始弧度
var endAngle = 0; //结束弧度
var color = '';
var time = 200; //毫秒数
var endTemp = '';
var angleStep = '';
for (var i = 0; i < data_arr.length; i++) {
//第一个扇形的起始角度
i == 0 ? startAngle = 0 : "";
//准备画扇形的数据
endAngle = startAngle + data_arr[i] * Math.PI * 2; //结束弧度
angleStep = (data_arr[i] * Math.PI * 2) / time; //画扇形时的增长步长
color = color_arr[i];
//开始画扇形
myLoop(startAngle, endAngle, ctx, angleStep, ox, oy, radius, color);
startAngle = endAngle;
}
}
/**
* 通过setInterval画圆
*/
function myLoop(startAngle, endAngle, ctx, angleStep, ox, oy, radius, color) {
var endTemp = startAngle; //画扇形时的动态增长的角度
var timer = setInterval(function() {
if (endTemp >= endAngle) {
clearInterval(timer);
return;
}
ctx.fillStyle = color;
endTemp += angleStep; //使临时结束弧度递增
ctx.beginPath();
ctx.moveTo(ox, oy); //曲线起点设置为圆心
ctx.arc(ox, oy, radius, startAngle, endTemp, false);
ctx.closePath();
ctx.fill();
}, 1);
}
/**
* 入口初始方法
*/
function init() {
//扇形比例数据和颜色
var data_arr = [0.3, 0.4, 0.2, 0.1];
var color_arr = ["#FF7F00", "#00FFFF", "#FFFF00", "#996633"];
drawCircle(data_arr, color_arr);
}
window.onload = init;
</script>
</head>
<body>
<h3>canvas绘制饼图</h3>
<p>
<canvas id="canvas_circle" width="500px" height="300px" style="border:2px solid #FF7F00">
您的浏览器不支持canvas
</canvas>
</p>
</body>
</html>