[js高手之路] html5 canvas系列教程 - arc绘制曲线图形(曲线,弧线,圆形)

绘制曲线,经常会用到路径的知识,如果你对路径有疑问,可以参考我的这篇文章[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度方向的一段圆弧:

 <style>
body {
background: #000;
}
#canvas{
background:white;
}
</style>
<script>
window.onload = function(){
var oCanvas = document.querySelector( "#canvas" ),
oGc = oCanvas.getContext( '2d' ),
width = oCanvas.width, height = oCanvas.height; oGc.arc( width / 2, height / 2, height / 2, 0, 270 * Math.PI / 180, true );
oGc.stroke();
}
</script>
</head>
<body>
<canvas id="canvas" width="600" height="300"></canvas>

如果是顺时针,就用这段:

oGc.arc( width / 2, height / 2, height / 2, 0, 270 * Math.PI / 180, false );
 
[js高手之路] html5 canvas系列教程 - arc绘制曲线图形(曲线,弧线,圆形)                                [js高手之路] html5 canvas系列教程 - arc绘制曲线图形(曲线,弧线,圆形)

如果采用闭合路径,弧度的起始点就会相连

 oGc.arc( width / 2, height / 2, height / 2, 0, 270 * Math.PI / 180, true );
oGc.closePath();
oGc.stroke();
 oGc.arc( width / 2, height / 2, height / 2, 0, 270 * Math.PI / 180, false );
oGc.closePath();
oGc.stroke();

[js高手之路] html5 canvas系列教程 - arc绘制曲线图形(曲线,弧线,圆形)                           [js高手之路] html5 canvas系列教程 - arc绘制曲线图形(曲线,弧线,圆形)

画两个不同颜色的圆形:

 <style>
body {
background: #000;
}
#canvas{
background:white;
}
</style>
<script>
window.onload = function(){
var oCanvas = document.querySelector( "#canvas" ),
oGc = oCanvas.getContext( '2d' ); oGc.beginPath();
oGc.strokeStyle = '#09f';
oGc.arc( 150, 150, 150, 0, 360 * Math.PI / 180 );
oGc.closePath();
oGc.stroke(); oGc.beginPath();
oGc.strokeStyle = 'orange';
oGc.arc( 450, 150, 150, 0, 360 * Math.PI / 180 );
oGc.closePath();
oGc.stroke();
}
</script>
</head>
<body>
<canvas id="canvas" width="600" height="300"></canvas>
</body>

画两个填充圆形,把上面的例子,stoke方式改成fill方式即可.

     oGc.beginPath();
oGc.fillStyle = '#09f';
oGc.arc( 150, 150, 150, 0, 360 * Math.PI / 180 );
oGc.closePath();
oGc.fill(); oGc.beginPath();
oGc.fillStyle = 'orange';
oGc.arc( 450, 150, 150, 0, 360 * Math.PI / 180 );
oGc.closePath();
oGc.fill();

画一个圆角:

 <style>
body {
background: #000;
}
#canvas{
background:white;
}
</style>
<script>
window.onload = function(){
var oCanvas = document.querySelector( "#canvas" ),
oGc = oCanvas.getContext( '2d' ); oGc.moveTo( 150, 50 );
oGc.lineTo( 250, 50 );
oGc.stroke(); oGc.beginPath();
oGc.arc( 250, 100, 50, 270 * Math.PI / 180, 0, false );
oGc.moveTo( 300, 100 );
oGc.lineTo( 300, 200 );
oGc.stroke();
}
</script>
</head>
<body>
<canvas id="canvas" width="600" height="300"></canvas>
</body>

[js高手之路] html5 canvas系列教程 - arc绘制曲线图形(曲线,弧线,圆形)

上一篇:【转】javascript 浮点数运算问题


下一篇:Unity5权威讲解