Morris.js 是一个轻量级的 JS 库,使用 jQuery 和 Raphaël 来生成各种时序图。
虽说现在移动手机网络已经到了4G,但是在移动web客户端开发过中,为了达到良好的体验效果,需要考虑很多的因素,比如板式,网速等等,最近有个任务需要在移动端显示<span>标签的内容,所有找js类的开源库,最终选择Morris.js ,一个是小,另外是支持移动包括iso和android,项目地址:点击打开链接,相比其他的开源库,这个上手还是比较简单的,可以看看官方的例子,但是有一些需要注意的地方:貌似x轴只能是已时间/日期为单位的(哈哈,还好我不要求)
第一步,导入相应的js文件:
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
第二步,在body标签内添加一个你需要放图的<div>标签,并添加相对应的id
<div id="myfirstchart" style="height: 250px;"></div>
第三步,就是写javascript代码了,参考实例:
<pre name="code" class="html">new Morris.Line({ // ID of the element in which to draw the chart. element: 'myfirstchart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: [ { year: '2008', value: 20 }, { year: '2009', value: 10 }, { year: '2010', value: 5 }, { year: '2011', value: 5 }, { year: '2012', value: 20 } ], // The name of the data record attribute that contains x-values. xkey: 'year', // A list of names of data record attributes that contain y-values. ykeys: ['value'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Value'] });
注意有时候希望横坐标不转换成对应的时间,可以加上
parseTime: false参考的;例子如下:
/* data stolen from http://howmanyleft.co.uk/vehicle/jaguar_'e'_type */ var month_data = [ {"period": "2012-10", "licensed": 3407, "sorned": 660}, {"period": "2011-08", "licensed": 3351, "sorned": 629}, {"period": "2011-03", "licensed": 3269, "sorned": 618}, {"period": "2010-08", "licensed": 3246, "sorned": 661}, {"period": "2010-05", "licensed": 3257, "sorned": 667}, {"period": "2010-03", "licensed": 3248, "sorned": 627}, {"period": "2010-01", "licensed": 3171, "sorned": 660}, {"period": "2009-12", "licensed": 3171, "sorned": 676}, {"period": "2009-10", "licensed": 3201, "sorned": 656}, {"period": "2009-09", "licensed": 3215, "sorned": 622} ]; Morris.Line({ element: 'graph', data: month_data, xkey: 'period', ykeys: ['licensed', 'sorned'], labels: ['Licensed', 'SORN'], smooth: false });
放一张效果图: