前端大全让前端飞

ionic + echart 绘制日历

2019-04-04  本文已影响2人  有梦想的风筝

前言
前段时间项目经理和我说要搞一个日历图表出来,思来想去最终还是决定用echarts去实现,上文提过echarts的基本运用方法(不了解的可以移步这里),这里就不在赘述。在这记录自己的实现过程与大家分享,有不当之处也希望大家可以指出。

引用

import echarts from 'echarts';

ionViewDidEnter(){
    let lunarData = [];
    //获取当前年月
    this.months = new Date().getMonth() + 1;
    this.years = new Date().getFullYear();
    if (this.months < 10) {
      this.months = '0' + this.months;
    }
    this.titinfo = this.years.toString() + '-' + this.months.toString();
    
   let myChart = echarts.init(<HTMLDivElement>document.getElementById('puEcharts'));
   
   //循环日历时间
   let dates = +echarts.number.parseDate(this.years + '-01-01');
      let end = +echarts.number.parseDate(this.years + '-12-31');
      let dayTime = 3600 * 24 * 1000;
      let datas = [];
      for (let time = dates; time <= end; time += dayTime) {
        datas.push([
          echarts.format.formatTime('yyyy-MM-dd', time),
          Math.floor(Math.random() * 10000)
        ]);
      }
     
     for (var i = 0; i < datas.length; i++) {
        lunarData.push([
          datas[i][0],
          1,
        ]);
      }

     let option = {
        calendar: [{
          left: 'center',
          top: 'middle',
          cellSize: [40, 40],
          yearLabel: { show: false },
          orient: 'vertical',
          dayLabel: {
            firstDay: 1,
            nameMap: 'cn'
          },
          monthLabel: {
            show: false
          },
          itemStyle: {
            normal: {
              borderWidth: 0
            }
          },
          splitLine: {
            show: false
          },
          range: this.titinfo//当前日历显示年月
        }],

        series: [{
          type: 'scatter',
          coordinateSystem: 'calendar',
          symbolSize: 1,
          label: {
            normal: {
              show: true,
              formatter: function(params) {
                var d = echarts.number.parseDate(params.value[0]);
                return d.getDate();
              },
              textStyle: {
                color: '#000',
                fontsize: 16
              }
            }
          },
          data: lunarData
        }]
      };
      myChart3.setOption(option);
}

成果图如下:


在这里插入图片描述

因为没有在echart中找到自由切换月份的方法,所有就自己写了一个。大概思路如下:
1.给左右键图标添加点击事件增减月份,并判断月份大于12或小于1时改变年份
2.将动态改变的年月赋值给option .range再初始化日历图表

到这基本就实现了日历的基本功能,整体思路就是日历坐标系+散点图,如果想在日历中DIV一些行程图例可以增加一组散点图渲染(参考官方图例)。如果对你有帮助的话记得点个赞!
(转载请注明出处)

上一篇下一篇

猜你喜欢

热点阅读