使用canvas绘制饼形图

绘制任意数据的简单饼形图

最终效果图

准备工作

1
2
3
4
5
6
7
8
9
10
// ===> 步骤 1
// 创建canvas标签,该标签用来展示图像
var canvas = document.createElement("canvas");
//canvas的宽高不要使用 CSS 来设置,会有拉伸问题,应该直接使用属性设置
canvas.width = 600;
canvas.height = 400;
canvas.style.border = '1px dashed red';
document.body.appendChild(canvas);
//获得绘图工具, 该工具是 CanvasRenderingContext2D 类型的对象.
var context = canvas.getContext('2d');

生成随机函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// ===> 步骤 2
//随机函数
var random = (function () {
//传入参数为两个,表示生成的数的个数在 min 和 max 之间取值
function randomWithTwoParam( min , max ) {
return Math.floor( ( max - min ) * Math.random() ) + min;
}
// 传入的参数为 1 个,表示生成的数的个数在 0 -max 之间取值
function randomWithOneParam( max ) {
return randomWithTwoParam( 0, max );
}
function random( min , max ) {
if ( min === undefined ) {
return Math.random();
} else if ( max === undefined ) {
return randomWithOneParam( min );
} else {
return randomWithTwoParam( min , max );
}
}
return random;
})();
//颜色
var colors = 'blueviolet,dodgerblue,orangered,limegreen,yellow,aqua,deeppink'.split( ',' );
//colors.length = 7;
//随机生成5-7个数
var count = random ( 5, colors.length);
//生成数字数组
var numbers = [];
while ( numbers.length <= count ) {
numbers.push( random (100) );
}

求生成的随机角度

1
2
3
4
5
6
7
8
9
10
11
12
// ===> 步骤 3
//求生成数字的总和
var sum = 0;
for( var i = 0; i < numbers.length; i++ ) {
sum += numbers[ i ];
}
//分析:
//生成的随机角数字 / 所对应的饼状图角度 = 生成数的总和 / (2*Math.PI)
var numObjs = numbers.map( v => ({
value: v,
angle: v * 2 * (Math.PI) / sum
}));

绘制饼状图

1
2
3
4
5
6
7
8
9
10
//===> 步骤 4
//循环绘制饼状图
var startAngel = -(Math.PI/2);
numObjs.forEach( function ( v , i ) {
context.beginPath();
context.fillStyle = colors[ i ];
context.moveTo( 300, 200 );
context.arc( 300, 200, 100, startAngel, startAngel += v.angle );
context.fill();
});

整合代码

代码整合: 将上述代码依次整合在一个script标签中,代码结束.

小结

饼状图只实现了大体功能,并未将数据添加到饼状图上,细节工作有待完善。