HTML5 新特性--用canvas(画布)来画圆

时间:2022-11-17 15:54:54

HTML部分:

1 <canvas id="canvas" width="32" height="32">
2    您的浏览器不支持canvas
3 </canvas>

 

js部分:

 1 function drawCircleInTd(v_id, v_n, v_percent) {
 2     var canvas = document.getElementById(v_id),
 3         context = canvas.getContext("2d"),
 4         cirX = canvas.width / 2,
 5         cirY = canvas.height / 2,
 6         rad = Math.PI * 2 / 100,
 7         n = parseFloat(v_n),
 8         speed_percent = 1,
 9         speed_text = 0.1;
10         var r = 14;
11 
12     //绘制最外层细圈
13     function writeCircle() {
14         context.save();         //save和restore可以保证样式属性只运用于该段canvas元素
15         context.beginPath();    //开始路径
16         context.strokeStyle = "#49f";       //设置边线的颜色
17         context.arc(cirX, cirY, r, 0, Math.PI * 2, false);      //画一个整圆.
18         context.stroke();       //绘制边线
19         context.restore();
20     }
21 
22     //绘制文本
23     function writeText(n) {
24         context.save();
25         context.strokeStyle = "#49f";
26         context.font = "10px Arial";  //设置字体大小和字体
27         context.strokeText(n.toFixed(0), cirX - 3, cirY + 5);  //这里改中心显示的数值和X,Y坐标.
28         context.stroke();
29         context.restore();
30     }
31 
32     //绘制蓝色外圈
33     function writeBlue(n) {
34         context.save();
35         context.strokeStyle = "#FA5377";
36         context.lineWidth = 4;
37         context.beginPath();
38         context.arc(cirX, cirY, r, -Math.PI / 2, -Math.PI / 2 + rad * n, false);      //这里改初始化百分比
39         // context.closePath();
40         // context.fill();
41         context.stroke();
42         context.restore();
43     }
44 
45     function DreamLoading() {
46         //清除所有,重新绘制
47         context.clearRect(0, 0, canvas.width, canvas.height)
48 
49         writeCircle();
50         writeText(speed_text);
51         writeBlue(speed_percent);
52 
53         if (speed_percent < v_percent) {
54             speed_percent++;
55         }
56         else {
57             context.closePath();
58         }
59 
60         if (speed_text < n) {
61             speed_text += 0.05;
62         }
63         else {
64             context.closePath();
65         }
66 
67         //setTimeout(DreamLoading,speed);
68         requestAnimationFrame(DreamLoading);
69     }
70 
71     DreamLoading();
72 }

 

最终效果图:

 HTML5 新特性--用canvas(画布)来画圆