2020年6月22日

微信小程序echarts使用附实用代码片段


微信小程序 引入echart 必须给ec-canvas标签外部定义一个box并且设置宽度和高度,不然图表不显示 直接设置给ec-canvas标签高度和宽度也不行

下载

下载ec-cavas地址:https://github.com/ecomfe/echarts-for-weixin

wxml


<div id="main" style="">

      <ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>
      </div>

json


{
  "usingComponents": {
    "ec-canvas": "../../ec-canvas/ec-canvas"
  }
}
js文件
import * as echarts from '../../ec-canvas/echarts';
let chart = null;
function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);
  var option = {
    grid:{
      y:"100rpx"
    },
    legend: {
      width:"5",
      left:"50",
      //itemHeight: 18,
        //itemWidth: 18,
      icon:"rect",
      padding:[0,0,0,0],
      //itemGap:"30rpx",
      textStyle:{
        fontSize:"20rpx",
        color:"#999999"
      }
    },
    tooltip: {},
    dataset: {
        source: [
            ['product', '收房次数', '出房次数'],
            ['05-01', 8, 6],
            ['05-02', 8, 6],
            ['05-03', 8, 6],
            ['05-04', 8, 6],
            ['05-05', 8, 6],
            ['05-06', 8, 6],
            ['05-07', 8, 6]
        ]
    },
    xAxis: {type: 'category',axisLine:{
                        lineStyle:{
                            color:'#999999'
                        }
                  },
                  axisLabel:{
                    textStyle:{
                      fontSize:'20rpx'
                    }
                  }
},
    yAxis: {
      axisLabel:{
        formatter:'{value}次',
        textStyle:{
          fontSize:"20rpx"
        }
      },
      axisLine:{
                        lineStyle:{
                            color:'#999999'
                        }
                    }
    },
    // Declare several bar series, each will be mapped
    // to a column of dataset.source by default.
    series: [
        {type: 'bar',itemStyle:{
          normal:{
            color:'#5acc83'
          }
        },barWidth : 20},
        {type: 'bar',itemStyle:{
          normal:{
            color:'#50a8f9'
          }
        },barWidth : 20}
    ],

  };
  chart.setOption(option);
  return chart;
}
Page({
  onShareAppMessage: function (res) {
    return {
      title: 'ECharts 可以在微信小程序中使用啦!',
      path: '/pages/index/index',
      success: function () { },
      fail: function () { }
    }
  },
  data: {
    ec: {
      onInit: initChart
    }
  },
  onReady() {
    setTimeout(function () {
      // 获取 chart 实例的方式
      // console.log(chart)
    }, 2000);
  }
});
wxss
  #main{
    position: relative; z-index: 9;
    width: 750rpx;height:405rpx;
  }

本文由专业的WEB前端外包公司-切图网原创,转载请保留版权( WEB前端开发外包www.qietu.com切图网始于2007年,提供高品质的前端开发服务、前端外包、切图外包。欢迎来电咨询!热线:027-81777732、13343477732