绘制曲线,经常会用到路径的知识,如果你对路径有疑问,可以参考我的这篇文章[js高手之路] html5 canvas系列教程 - 开始路径beginPath与关闭路径closePath详解.
arc:画弧度
cxt.arc( x, y, 半径, 开始角度,结束角度,是否逆时针 );
x, y: 为弧度的中心横坐标和纵坐标,如果这是画一个圆.那么x,y就是圆的圆心.
开始角度与结束角度都是以弧度单位,弧度与角度的换算关系为: 弧度=角度*(π/180°)。
以时钟为参考,3点钟方向为0度,6点钟方向为90度,9点钟方向为180度,12点钟方向为270度.
第五个参数:true为逆时针,false为顺时针,默认值为false
在canvas的中心,换一个从0度方向开始,逆时针到270度方向的一段圆弧:
1 <style>
2 body {
3 background: #000;
4 }
5 #canvas{
6 background:white;
7 }
8 </style>
9 <script>
10 window.onload = function(){
11 var oCanvas = document.querySelector( "#canvas" ),
12 oGc = oCanvas.getContext( '2d' ),
13 width = oCanvas.width, height = oCanvas.height;
14
15 oGc.arc( width / 2, height / 2, height / 2, 0, 270 * Math.PI / 180, true );
16 oGc.stroke();
17 }
18 </script>
19 </head>
20 <body>
21 <canvas id="canvas" width="600" height="300"></canvas>
如果是顺时针,就用这段:
oGc.arc( width / 2, height / 2, height / 2, 0, 270 * Math.PI / 180, false );
![](https://i-blog.csdnimg.cn/blog_migrate/aa6f4443516b4edc6fe36dda35749aca.png)
![](https://i-blog.csdnimg.cn/blog_migrate/fdf80d82c991b4c88e6618756680cc8b.png)
如果采用闭合路径,弧度的起始点就会相连
1 oGc.arc( width / 2, height / 2, height / 2, 0, 270 * Math.PI / 180, true );
2 oGc.closePath();
3 oGc.stroke();
1 oGc.arc( width / 2, height / 2, height / 2, 0, 270 * Math.PI / 180, false );
2 oGc.closePath();
3 oGc.stroke();
画两个不同颜色的圆形:
1 <style>
2 body {
3 background: #000;
4 }
5 #canvas{
6 background:white;
7 }
8 </style>
9 <script>
10 window.onload = function(){
11 var oCanvas = document.querySelector( "#canvas" ),
12 oGc = oCanvas.getContext( '2d' );
13
14 oGc.beginPath();
15 oGc.strokeStyle = '#09f';
16 oGc.arc( 150, 150, 150, 0, 360 * Math.PI / 180 );
17 oGc.closePath();
18 oGc.stroke();
19
20 oGc.beginPath();
21 oGc.strokeStyle = 'orange';
22 oGc.arc( 450, 150, 150, 0, 360 * Math.PI / 180 );
23 oGc.closePath();
24 oGc.stroke();
25 }
26 </script>
27 </head>
28 <body>
29 <canvas id="canvas" width="600" height="300"></canvas>
30 </body>
画两个填充圆形,把上面的例子,stoke方式改成fill方式即可.
1 oGc.beginPath();
2 oGc.fillStyle = '#09f';
3 oGc.arc( 150, 150, 150, 0, 360 * Math.PI / 180 );
4 oGc.closePath();
5 oGc.fill();
6
7 oGc.beginPath();
8 oGc.fillStyle = 'orange';
9 oGc.arc( 450, 150, 150, 0, 360 * Math.PI / 180 );
10 oGc.closePath();
11 oGc.fill();
画一个圆角:
1 <style>
2 body {
3 background: #000;
4 }
5 #canvas{
6 background:white;
7 }
8 </style>
9 <script>
10 window.onload = function(){
11 var oCanvas = document.querySelector( "#canvas" ),
12 oGc = oCanvas.getContext( '2d' );
13
14 oGc.moveTo( 150, 50 );
15 oGc.lineTo( 250, 50 );
16 oGc.stroke();
17
18 oGc.beginPath();
19 oGc.arc( 250, 100, 50, 270 * Math.PI / 180, 0, false );
20 oGc.moveTo( 300, 100 );
21 oGc.lineTo( 300, 200 );
22 oGc.stroke();
23 }
24 </script>
25 </head>
26 <body>
27 <canvas id="canvas" width="600" height="300"></canvas>
28 </body>