标签:
**H5 简单几步实现柱状图,饼状图**
<!doctype html>
<meta charset="utf-8">
<html>
<head>
<meta charset="UTF-8">
<title>饼状图</title>
</head>
<body>
<div align="center">
<canvas id="myCanvas" width="300" height="300" style="border:1px solide:#325CA5;"></canvas>
</div>
<script type="text/javascript">
var color=[‘#FFFF00‘,‘red‘,‘blue‘,‘#FF7F00‘,‘#FF4500‘,‘#EE1289‘,‘#D3D3D3‘,‘#FF83FA‘,‘#ADFF2F‘,‘#8B2323‘,‘#7FFF00‘,‘#48D1CC‘,‘#00FFFF‘,‘#00EE00‘,‘#000000‘,‘#8B0A50‘,‘#8B7500‘,‘#A0522D‘];
var percent=[15,35,50];
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var chartRadius = canvas.height / 2;
var startPoint = 2*Math.PI*1.5;
for(var i=0;i<percent.length;i++)
{
ctx.beginPath();
ctx.moveTo(centerX,centerY);
ctx.fillStyle=color[i];
ctx.arc(centerX,centerY,chartRadius,startPoint,startPoint-2*Math.PI*(percent[i]/100),true);
ctx.closePath();
ctx.fill();
startPoint-=2*Math.PI*(percent[i]/100);
}
</script>
</body>
</html>
如果是画扇形图那么久不要循环就OK,原理就是移动到ctx.moveTo(centerX,centerY) 处,画一段弧 ctx.arc(centerX,centerY,chartRadius,startPoint,startPoint-2*Math.PI*(percent[i]/100),true) 五个参数分别是 圆心,半径,起始点,终止点,是否顺时针
<!DOCTYPE html>
<html>
<head><title>chart demo</title>
<style>
#chartContainer{
border:solid 1px #999;
}
</style>
<script src="http://cloud.github.com/downloads/scottkiss/H5Draw/H5Draw.js"></script>
<script src="http://cloud.github.com/downloads/scottkiss/H5Draw/h5Charts.js"></script>
<script>
window.onload = function(){
var chart = new h5Charts.SerialChart();
chart.dataProvider = [{age:"18",amount:10},{age:"38",amount:30},{age:"8",amount:6},{age:"29",amount:20}];
chart.categoryField = "age";
chart.valueField = "amount";
chart.type = "column";
chart.columnWidth = 55;
chart.colors = ["#f00","#0f0","#0ff","#00f"];
chart.addTo("chartContainer");
};
</script>
</head>
<body>
<canvas id="chartContainer" width="500" height="400">
browser doesn‘t support html5
</canvas>
</body>
</html>
上面的程序首先引入了需要js文件,分别是H5Draw.js和h5Charts.js。其中H5Draw.js是对canvas api的简单封装,在h5Charts.js中会使用H5Draw.js中提供的绘图函数,h5Charts.js便是绘制柱状图的内部实现。在这里,我们不需要知道内部具体如何实现,只要实例化一个柱状图的chart对象,然后给chart对象设置需要的属性即可,其中dataProvider属性就是需要进行可视化展示的用户数据,这里的type是column便是柱状图。最后调用chart对象的addTo函数,将该对象添加到指定的canvas元素中,就完成了。
标签:
原文地址:http://blog.csdn.net/u013430371/article/details/51352757