与setTimeout和setInterval不同,requestAnimationFrame不需要设置时间间隔。
效果图
源代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Canvas progress</title>
</head>
<body><div style='width:660px;height:400px; text-align:center;'><canvas id="process" width="200" height="200"></canvas></div><script>(function (){var c = document.getElementById('process'),process = 0,ctx = c.getContext('2d');// 画灰色的圆ctx.beginPath();ctx.arc(100, 100, 80, 0, Math.PI*2);ctx.closePath();ctx.fillStyle = '#F6F6F6';ctx.fill();function animate(){requestAnimationFrame(function (){process = process + 1;drawCricle(ctx, process);if (process < 100) {animate();}});}function drawCricle(ctx, percent){// 画进度环ctx.beginPath();ctx.moveTo(100, 100); ctx.arc(100, 100, 80, Math.PI * 1.5, Math.PI * (1.5 + 2 * percent / 100 ));ctx.closePath();ctx.fillStyle = '#FF9600';ctx.fill();// 画内填充圆ctx.beginPath();ctx.arc(100, 100, 75, 0, Math.PI * 2);ctx.closePath();ctx.fillStyle = '#fff';ctx.fill();// 填充文字ctx.font = "bold 20pt Microsoft YaHei"; ctx.fillStyle = '#333';ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.moveTo(100, 100); ctx.fillText(process + '%', 100, 100);}animate();}());</script>
</body>
</html>