1、绘制圆形(arc)
概述:arc() 方法创建弧/曲线(用于创建圆或部分圆)。
* 语法:ctx.arc(x , y, r, sAngle, eAngle, counterclockwise);
* arc: 弧(度)弧形物;天穹 英 [ɑːk] 美 [ɑrk]
* counter 反击,还击;反向移动,对着干;反驳,回答 ['kaʊntə] 美 ['kaʊntɚ]
* 解释:
- x,y:圆心坐标。
- r:半径大小。
- sAngle:绘制开始的角度。 圆心到最右边点是0度,顺时针方向弧度增大。
- eAngel:结束的角度,注意是弧度。π
- counterclockwise:是否是逆时针。true是逆时针,false:顺时针,默认false;
- 弧度和角度的转换公式: rad = deg*Math.PI/180;
- 在Math提供的方法中**sin、cos等都使用的弧度**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圆、扇形</title>
</head>
<body>
<div id="container">
<canvas id="cavsElem">
你的浏览器不支持canvas,请升级浏览器
</canvas>
</div>
<script>
(function(){
var canvas = document.getElementById('cavsElem');
var ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 600;
canvas.style.border = '1px solid red';
ctx.strokeStyle = 'red';
ctx.lineWidth = 6;
//绘制300度的扇形,逆时针绘制,从圆心到弧线起点,再到终点,再闭合
ctx.moveTo(100,100);
ctx.arc(100,100,100,0*Math.PI/180,60*Math.PI/180,true);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = 'pink';
ctx.fill();
//绘制120度的弧线,从弧线起点开始到弧线终点
ctx.beginPath();
ctx.moveTo(200,400);
ctx.arc(100,400,100,0*Math.PI/180,120*Math.PI/180);
// ctx.closePath();
ctx.stroke();
//绘制60度的扇形,顺时针绘制
ctx.beginPath();
ctx.moveTo(200,200);
ctx.arc(200,200,100,0*Math.PI/180,60*Math.PI/180);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = 'yellow';
ctx.fill();
//绘制圆,从起点到终点
ctx.beginPath();
ctx.moveTo(500,400);
ctx.arc(400,400,100,0*Math.PI/180,360*Math.PI/180);
ctx.stroke();
ctx.fillStyle = 'green';
ctx.fill();
})();
</script>
</body>
</html>
效果:
2、饼状图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>饼状图</title>
</head>
<body>
<div id="container">
<canvas id="cavsElem">
您的浏览器不支持canvas,请升级浏览器
</canvas>
</div>
<script>
(function(){
var canvas = document.getElementById('cavsElem');
var ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 600;
canvas.style.border = '1px solid red';
var data = [{
"value": .2,
"color": "red",
"title": "大专"
},{
"value": .4,
"color": "blue",
"title": "本科"
},{
"value": .3,
"color": "green",
"title": "硕士"
},{
"value": .1,
"color": "pink",
"title": "博士"
}];
//定义起始角度
var tempAngle=-90;
//定圆心位置
var x0=300,y0=300;
//定半径长度
var radius=200;
//从-90度开始绘制
for(var i=0; i<data.length; i++){
ctx.beginPath();
ctx.moveTo(x0,y0);
//当前扇形角度
var angle = data[i].value*360;
//当前扇形起始绘制弧度
var startAngle = tempAngle*Math.PI/180;
//当前扇形借结束绘制弧度
var endAngle = (tempAngle + angle)*Math.PI/180;
//绘制扇形
ctx.arc(x0,y0,radius,startAngle,endAngle);
ctx.stroke();
//填充扇形
ctx.fillStyle = data[i].color;
ctx.fill();
//当前扇形结束绘制角度,即下一个扇形开始绘制角度
tempAngle += angle;
}
})();
</script>
</body>
</html>
效果: