uni小程序和App的echarts图表使用

  • echarts图表
<template>
 <div>
   <!-- #ifdef APP-PLUS-->
   <view class="echarts">
     <e-charts-vue v-if="options" id="echartsPrice" :height="460" :options="options" />
   </view>
   <!-- #endif -->
   <!-- #ifdef MP-->
   <view class="echarts">
     <wx-chart-canvas id="lineChart" ref="canvas" class="wx-chart-canvas" canvas-id="wx-chart-canvas" :ec="ec">
     </wx-chart-canvas>
   </view>
   <!-- #endif -->
 </div>
</template>

<script>
export default {
 data() {
   return {
     option: '',
     ec: {
       option: '',
     },
     options: {}
   }
 },
 onLoad(val) {
   this.option = val
   this._getEchartDate(val)
 },
 methods: {
   // 获取图表数据
   async _getEchartDate(option) {
     // let quotationDate = dayjs(this.item.add_time).format('YYYY-MM-DD')
     try {
       const params = {
         id: 1234567
       }
       const res = await getTrend(params)
       if (res.Code === 200) {
         this.chartY = res.Data.price || []
         this.chartX = res.Data.date || []
         this.initLineEcharts(this.chartX, this.chartY)
       }
     } catch (err) {
       console.log(err)
     }
   },
   initChart(canvas, width, height, canvasDpr) {
     chart = echarts.init(canvas, null, {
       width: width,
       height: height,
       devicePixelRatio: canvasDpr
     })
     canvas.setChart(chart)
     chart.setOption(this.ec.option)
     return chart
   },
   // 初始化(折线图)
   initLineEcharts(chartX, chartY) {
     let min = Math.floor(Math.min(...chartY) / 1.05)
     let max = Math.ceil(Math.max(...chartY) * 1.05)
     let interval = (max - min) / 5;
     let chartOptions = {
       grid: {
         top: 30,
         bottom: 32,
         left: (this.item?.mainclass_id === 6) ? 68 : 58,
         right: 22,
       },
       tooltip: {
         trigger: 'axis',
         axisPointer: {
           type: 'line',
           axis: 'x',
         },
         label: {
           show: true,
         },
       },
       xAxis: {
         type: 'category',
         show: true,
         data: chartX,
         nameLocation: 'start',
       },
       yAxis: {
         type: 'value',
         name: this.item.unit || '元/吨',
         nameLocation: 'end',
         nameTextStyle: {
           verticalAlign: 'middle',
         },
         scale: true,
         axisLine: {
           lineStyle: {
             color: '#666',
           },
         },
         splitLine: {
           show: true,
           lineStyle: {
             color: '#e3e3e3',
           },
         },
         min: min,
         max: max,
         splitNumber: 4,
         interval: interval,
       },
       color: ['#4167a8'],
       series: [{
         type: 'line',
         name: `参考价`,
         data: chartY,
         showSymbol: false,
         lineStyle: {
           width: 1,
         },
       },],
     }
     // #ifdef APP-PLUS
     this.options = chartOptions
     // #endif

     // #ifdef MP
     this.ec.option = chartOptions
     this.$nextTick(() => {
       this.$refs.canvas.init(this.initChart)
     });
     // #endif
   },
 },
}
</script>

<style lang=scss></style>
  • 安装echarts@5.2.2
  • 微信小程序展示的echarts:index.vue
<template>
  <canvas type="2d" v-if="isUseNewCanvas" class="ec-canvas" :canvas-id="canvasId" @init="init" @touchstart="touchStart"
    @touchmove="touchMove" @touchend="touchEnd">
  </canvas>
  <canvas v-else class="ec-canvas" :canvas-id="canvasId" @init="init" @touchstart="touchStart" @touchmove="touchMove"
    @touchend="touchEnd">
  </canvas>
</template>

<script>
import WxCanvas from "./wx-canvas";
import * as echarts from "echarts";

let ctx;

function wrapTouch(event) {
  for (let i = 0; i < event.touches.length; ++i) {
    const touch = event.touches[i];
    touch.offsetX = touch.x;
    touch.offsetY = touch.y;
  }
  return event;
}

export default {
  props: {
    canvasId: {
      type: String,
      default: () => {
        return "ec-canvas";
      }
    },
    ec: {
      type: Object
    },
    forceUseOldCanvas: {
      type: Boolean,
      value: false
    }
  },
  data() {
    return {
      $curChart: {},
      toHandleList: [],
      isUseNewCanvas: true
    };
  },
  watch: {
    "ec.option": {
      deep: true,
      handler(val, oldVal) {
        this.setOption(val);
      }
    }
  },
  onReady: function () {
    if (!this.ec) {
      console.warn(
        '组件需绑定 ec 变量,例:<ec-canvas id="mychart-dom-bar" ' +
        'canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>'
      );
      return;
    }
    if (!this.ec.lazyLoad) {
      this.init();
    }
  },
  methods: {
    compareVersion(v1, v2) {
      v1 = v1.split(".");
      v2 = v2.split(".");
      const len = Math.max(v1.length, v2.length);

      while (v1.length < len) {
        v1.push("0");
      }
      while (v2.length < len) {
        v2.push("0");
      }

      for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i]);
        const num2 = parseInt(v2[i]);

        if (num1 > num2) {
          return 1;
        } else if (num1 < num2) {
          return -1;
        }
      }
      return 0;
    },
    init(callback) {
      const version = wx.getSystemInfoSync().SDKVersion;

      let canUseNewCanvas = this.compareVersion(version, "2.9.0") >= 0;
      if (this.forceUseOldCanvas) {
        if (canUseNewCanvas) console.warn("开发者强制使用旧canvas,建议关闭");
        canUseNewCanvas = false;
      }
      this.isUseNewCanvas = canUseNewCanvas && !this.forceUseOldCanvas;
      if (this.isUseNewCanvas) {
        console.log('微信基础库版本大于2.9.0,开始使用<canvas type="2d"/>');
        // 2.9.0 可以使用 <canvas type="2d"></canvas>
        this.initByNewWay(callback);
      } else {
        const isValid = this.compareVersion(version, "1.9.91") >= 0;
        if (!isValid) {
          console.error(
            "微信基础库版本过低,需大于等于 1.9.91。" +
            "参见:https://github.com/ecomfe/echarts-for-weixin" +
            "#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82"
          );
          return;
        } else {
          console.warn(
            "建议将微信基础库调整大于等于2.9.0版本。升级后绘图将有更好性能"
          );
          this.initByOldWay(callback);
        }
      }
    },
    initByOldWay(callback) {
      // 1.9.91 <= version < 2.9.0:原来的方式初始化
      ctx = wx.createCanvasContext(this.canvasId, this);
      const canvas = new WxCanvas(ctx, this.canvasId, false);
      const that = this
      echarts.setCanvasCreator(() => {
        return canvas;
      });
      // const canvasDpr = wx.getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr
      const canvasDpr = 1;
      var query = wx.createSelectorQuery().in(this);
      query
        .select(".ec-canvas")
        .boundingClientRect(res => {
          if (typeof callback === "function") {
            that.$curChart = callback(canvas, res.width, res.height, canvasDpr);
          } else if (that.ec) {
            that.initChart(canvas, res.width, res.height, canvasDpr)
          } else {
            that.triggerEvent("init", {
              canvas: canvas,
              width: res.width,
              height: res.height,
              devicePixelRatio: canvasDpr // 增加了dpr,可方便外面echarts.init
            });
          }
        })
        .exec();
    },
    initByNewWay(callback) {
      const that = this
      // version >= 2.9.0:使用新的方式初始化
      const query = wx.createSelectorQuery().in(this);
      query
        .select(".ec-canvas")
        .fields({
          node: true,
          size: true
        })
        .exec(res => {
          const canvasNode = res[0].node;

          const canvasDpr = wx.getSystemInfoSync().pixelRatio;
          const canvasWidth = res[0].width;
          const canvasHeight = res[0].height;

          const ctx = canvasNode.getContext("2d");

          const canvas = new WxCanvas(ctx, that.canvasId, true, canvasNode);
          echarts.setCanvasCreator(() => {
            return canvas;
          });

          if (typeof callback === "function") {
            that.$curChart = callback(
              canvas,
              canvasWidth,
              canvasHeight,
              canvasDpr
            );
          } else if (that.ec) {
            that.initChart(canvas, canvasWidth, canvasHeight, canvasDpr)
          } else {
            that.triggerEvent("init", {
              canvas: canvas,
              width: canvasWidth,
              height: canvasHeight,
              devicePixelRatio: canvasDpr
            });
          }
        });
    },
    setOption(val) {
      if (!this.$curChart || !this.$curChart.setOption) {
        this.toHandleList.push(val);
      } else {
        this.$curChart.setOption(val);
      }
    },
    canvasToTempFilePath(opt) {
      if (this.isUseNewCanvas) {
        // 新版
        const query = wx.createSelectorQuery().in(this);
        query
          .select(".ec-canvas")
          .fields({
            node: true,
            size: true
          })
          .exec(res => {
            const canvasNode = res[0].node;
            opt.canvas = canvasNode;
            wx.canvasToTempFilePath(opt);
          });
      } else {
        // 旧的
        if (!opt.canvasId) {
          opt.canvasId = this.canvasId;
        }
        ctx.draw(true, () => {
          wx.canvasToTempFilePath(opt, this);
        });
      }
    },

    touchStart(e) {
      if (this.ec.stopTouchEvent) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }
      this.$emit("touchstart", e);
      if (this.$curChart && e.touches.length > 0) {
        var touch = e.touches[0];
        var handler = this.$curChart.getZr().handler;
        if (handler) {
          handler.dispatch("mousedown", {
            zrX: touch.x,
            zrY: touch.y
          });
          handler.dispatch("mousemove", {
            zrX: touch.x,
            zrY: touch.y
          });
          handler.processGesture(wrapTouch(e), "start");
        }
      }
    },

    touchMove(e) {
      if (this.ec.stopTouchEvent) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }
      this.$emit("touchmove", e);
      if (this.$curChart && e.touches.length > 0) {
        var touch = e.touches[0];
        var handler = this.$curChart.getZr().handler;
        if (handler) {
          handler.dispatch("mousemove", {
            zrX: touch.x,
            zrY: touch.y
          });
          handler.processGesture(wrapTouch(e), "change");
        }
      }
    },

    touchEnd(e) {
      if (this.ec.stopTouchEvent) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }
      this.$emit("touchend", e);
      if (this.$curChart) {
        const touch = e.changedTouches ? e.changedTouches[0] : {};
        var handler = this.$curChart.getZr().handler;
        if (handler) {
          handler.dispatch("mouseup", {
            zrX: touch.x,
            zrY: touch.y
          });
          handler.dispatch("click", {
            zrX: touch.x,
            zrY: touch.y
          });
          handler.processGesture(wrapTouch(e), "end");
        }
      }
    },

    initChart(canvas, width, height, canvasDpr) {
      this.$curChart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: canvasDpr
      });
      canvas.setChart(this.$curChart);
      this.$curChart.setOption(this.ec.option);
    }
  }
};
</script>

<style lang="scss">
.ec-canvas {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
  • 微信wx-canvas.js
export default class WxCanvas {
  constructor(ctx, canvasId, isNew, canvasNode) {
    this.ctx = ctx;
    this.canvasId = canvasId;
    this.chart = null;
    this.isNew = isNew
    if (isNew) {
      this.canvasNode = canvasNode;
    } else {
      this._initStyle(ctx);
    }

    // this._initCanvas(zrender, ctx);

    this._initEvent();
  }

  getContext(contextType) {
    if (contextType === '2d') {
      return this.ctx;
    }
  }

  // canvasToTempFilePath(opt) {
  //   if (!opt.canvasId) {
  //     opt.canvasId = this.canvasId;
  //   }
  //   return wx.canvasToTempFilePath(opt, this);
  // }

  setChart(chart) {
    this.chart = chart;
  }

  attachEvent() {
    // noop
  }

  detachEvent() {
    // noop
  }

  _initCanvas(zrender, ctx) {
    zrender.util.getContext = function () {
      return ctx;
    };

    zrender.util.$override('measureText', function (text, font) {
      ctx.font = font || '12px sans-serif';
      return ctx.measureText(text);
    });
  }

  _initStyle(ctx) {
    var styles = ['fillStyle', 'strokeStyle', 'globalAlpha',
      'textAlign', 'textBaseAlign', 'shadow', 'lineWidth',
      'lineCap', 'lineJoin', 'lineDash', 'miterLimit', 'fontSize'
    ];

    styles.forEach(style => {
      Object.defineProperty(ctx, style, {
        set: value => {
          if (style !== 'fillStyle' && style !== 'strokeStyle' ||
            value !== 'none' && value !== null
          ) {
            ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
          }
        }
      });
    });

    ctx.createRadialGradient = () => {
      return ctx.createCircularGradient(arguments);
    };
  }

  _initEvent() {
    this.event = {};
    const eventNames = [{
      wxName: 'touchStart',
      ecName: 'mousedown'
    }, {
      wxName: 'touchMove',
      ecName: 'mousemove'
    }, {
      wxName: 'touchEnd',
      ecName: 'mouseup'
    }, {
      wxName: 'touchEnd',
      ecName: 'click'
    }];

    eventNames.forEach(name => {
      this.event[name.wxName] = e => {
        const touch = e.touches[0];
        this.chart.getZr().handler.dispatch(name.ecName, {
          zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
          zrY: name.wxName === 'tap' ? touch.clientY : touch.y
        });
      };
    });
  }

  set width(w) {
    if (this.canvasNode) this.canvasNode.width = w
  }
  set height(h) {
    if (this.canvasNode) this.canvasNode.height = h
  }

  get width() {
    if (this.canvasNode)
      return this.canvasNode.width
    return 0
  }
  get height() {
    if (this.canvasNode)
      return this.canvasNode.height
    return 0
  }
}
  • APP展示的echarts:index.vue
<template>
  <!-- #ifdef APP-PLUS || H5 -->
  <view @click="echarts && echarts.onClick" :prop="option" :change:prop="echarts && echarts.updateEcharts" :id="id"
    class="echarts" :style="{
    width: typeof width === 'number' ? width + 'rpx' : width,
    height: height + 'rpx'
  }">
  </view>
  <!-- #endif -->
</template>

<script>
export default {
  props: {
    options: {
      type: Object,
      default: () => ({}),
    },
    width: {
      type: [Number, String],
      default: () => '100%',
    },
    height: {
      type: Number,
      default: 200,
    },
    // 动态传id
    id: {
      type: String,
      dafault: 'echarts',
    },
  },
  watch: {
    options: {
      handler(newValue, oldValue) {
        this.option = newValue
      },
      immediate: true,
      deep: true, // 深度监听
    },
  },
  methods: {
    onViewClick(value) {
      console.log('service 层方法', value)
    },
  },
}
</script>

<script module="echarts" lang="renderjs">
let myChart
export default {
  mounted() {
    if (typeof window.echarts === 'function') {
      this.initEcharts()
    } else {
      // 动态引入较大类库避免影响页面展示
      const script = document.createElement('script')
      // view 层的页面运行在 www 根目录,其相对路径相对于 www 计算
      script.src = 'https://css.ccement.com/js/cdn/uniapp/echarts.min.js'
      script.onload = this.initEcharts.bind(this)
      document.head.appendChild(script)
    }
  },
  methods: {
    initEcharts() {
      myChart = echarts.init(document.getElementById(this.id),null,{renderer:'svg'})
      if(this.id !== 'echartsPrice'){
        this.option.xAxis.axisLabel.formatter = function formatter(value) {
          var date = new Date(value)
          var year = date.getFullYear()
          var month = date.getMonth() + 1
          var day = date.getDate()
          return year + '-' + (month > 9 ? month : '0' + month) + '-' + (day > 9 ? day : '0' + day)
        }
        this.option.xAxis.min =  (value) => {
          return value.min - 30 * 24 * 60 * 60 * 1000
        }
        this.option.xAxis.max =  (value) => {
          return value.max + 30 * 24 * 60 * 60 * 1000
        }
        this.option.yAxis.min = (value) => {
          return value.min - 10
        }
        this.option.yAxis.max = (value) => {
          return value.max + 10
        }
      }else{
        // 价格详情过来的
        this.option.yAxis.min = (value) => {
          return Math.floor(value.min / 1.05)
        }
        this.option.tooltip.formatter = (params)=> {
          return `${params[0]?.name}<br/>参考价:${params[0].value}`
        }
      }
      console.log(this.option);
      // 观测更新的数据在 view 层可以直接访问到
      myChart &&  myChart.setOption(this.option)
    },
    updateEcharts(newValue, oldValue, ownerInstance, instance) {
      // 监听 service 层数据变更
      myChart && myChart.setOption(newValue)
    },
    onClick(event, ownerInstance) {
      // 调用 service 层的方法
      ownerInstance.callMethod('onViewClick', {
        test: 'test'
      })
    }
  }
}
</script>

<style>
.echarts {
  width: 100%;
  height: 300px;
}
</style>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,080评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,422评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,630评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,554评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,662评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,856评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,014评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,752评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,212评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,541评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,687评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,347评论 4 331
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,973评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,777评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,006评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,406评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,576评论 2 349

推荐阅读更多精彩内容