在小程序中使用echarts

1、安装依赖

npm install echarts mpvue-echarts --save

下载成功后在node_modules里面会多出 echartsmpvue-echatszrender 三个目录,将mpvue-echats目录下的src目录放进components文件夹中,由于小程序包大小限制,可以定制化echcarts并根据自身框架引入

2、封装组件
完整代码, 由于小程序canvas层级过高导致的各种bug,这里辽转base64处理

    <template>
      <view class="ec-canvas">
        <canvas v-if="canvasId && !imgBase64" class="ec-canvas" :id="canvasId" :canvasId="canvasId" @touchstart="touchStart"
          @touchmove="touchMove" @touchend="touchEnd" @error="error"></canvas>
          <img class="ec-canvas" :src="imgBase64" />
      </view>
    </template>
    
    <script>
      import WxCanvas from './wx-canvas';
      import * as echarts from '@/static/libs/echarts/echarts.min'; /*chart.min.js为在线定制*/
    
      export default {
        props: {
       	  canvasId: {
            type: String,
            default: 'ec-canvas'
          },
          lazyLoad: {
            type: Boolean,
            default: false
          },
          disableTouch: {
            type: Boolean,
            default: true
          },
          throttleTouch: {
            type: Boolean,
            default: true
          }
        },
        data(){
          return {
            imgBase64: ''
          }
        },
        onReady() {
          if (!echarts) {
            console.warn('组件需绑定 echarts 变量,例:<ec-canvas id="mychart-dom-bar" ' +
              'canvas-id="mychart-bar" :echarts="echarts"></ec-canvas>');
            return;
          }
          if (!this.lazyLoad) this.init();
        },
        methods: {
          init() {
            let self = this;
            const version = wx.version.version.split('.').map(n => parseInt(n, 10));
            const isValid = version[0] > 1 || (version[0] === 1 && version[1] > 9) || (version[0] === 1 && version[1] ===
              9 && version[2] >= 91);
            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;
            }
    
    
            const canvasId = this.canvasId;
            this.ctx = wx.createCanvasContext(canvasId, this);
    
            const canvas = new WxCanvas(this.ctx, canvasId);
    
            echarts.setCanvasCreator(() => canvas);
    
            const query = wx.createSelectorQuery().in(this);
            query
              .select(`#${canvasId}`)
              .boundingClientRect(res => {
                if (!res) {
                  //setTimeout(() => this.init(), 200);  
                  return;
                }
    
                this.chart = this.$emit('onInit', {
                  canvas,
                  width: res.width,
                  height: res.height
                });
                setTimeout(() => {
                  self.canvasToImg({
                    width: res.width,
                    height: res.height
                  })
                }, 500);  
              })
              .exec();
          },
          canvasToTempFilePath(opt) {
            const {
              canvasId
            } = this;
            this.ctx.draw(true, () => {
              wx.canvasToTempFilePath({
                canvasId,
                ...opt
              });
            });
          },
          touchStart(e) {
            const {
              disableTouch
            } = this;
            if (disableTouch || !e.mp.touches.length) return;
            const touch = e.mp.touches[0];
            echarts._zr.handler.dispatch('mousedown', {
              zrX: touch.x,
              zrY: touch.y
            });
            echarts._zr.handler.dispatch('mousemove', {
              zrX: touch.x,
              zrY: touch.y
            });
          },
          touchMove(e) {
            const {
              disableTouch,
              throttleTouch,
              lastMoveTime
            } = this;
            if (disableTouch || !e.mp.touches.length) return;
    
            if (throttleTouch) {
              const currMoveTime = Date.now();
              if (currMoveTime - lastMoveTime < 240) return;
              this.lastMoveTime = currMoveTime;
            }
    
            const touch = e.mp.touches[0];
            echarts._zr.handler.dispatch('mousemove', {
              zrX: touch.x,
              zrY: touch.y
            });
          },
          touchEnd(e) {
            const {
              disableTouch
            } = this;
            if (disableTouch) return;
            const touch = e.mp.changedTouches ? e.mp.changedTouches[0] : {};
            echarts._zr.handler.dispatch('mouseup', {
              zrX: touch.x,
              zrY: touch.y
            });
            echarts._zr.handler.dispatch('click', {
              zrX: touch.x,
              zrY: touch.y
            });
          },
          // canvas转图片
          canvasToImg(options){
            let self = this;
            uni.canvasToTempFilePath({
                x: 0, // 起点坐标
                y: 0,
                width: options.width, // canvas 宽
                height: options.height, // canvas 高
                canvasId: self.canvasId, // canvas id
                success(res) {
                  
                  const savedFilePath = res.tempFilePath //相对路径
                  uni.getFileSystemManager().readFile({
                      filePath: savedFilePath, //选择图片返回的相对路径
                      encoding: 'base64', //编码格式
                      success: res1 => { //成功的回调
                          self.imgBase64 = 'data:image/jpeg;base64,' + res1.data //不加上这串字符,在页面无法显示的哦
                      },fail: (e) => {
                          self.imgBase64 = savedFilePath;
                          console.log("图片转换失败");
                      }
                  })
                },
                fail(err){
                  console.log(err)
                }
            },this)   
          }
        }
      };
    </script>
    
    <style scoped>
      .ec-canvas {
        width: 100%;
        height: 100%;
        flex: 1;
      }
    </style>

3、在页面中使用(可去echarts官网在线调试好后直接复制配置项)

<template>
	<view class="me-healthData box">
		<view class="line">
			<mpvue-echarts id="main" ref="mapChart" @onInit="renderLine" />
			<text v-if="!loading">最近到店(近七次)</text>
		</view>
		<mpvue-echarts id="main2" ref="mapChart2" canvasId='ec-canvas2' @onInit="renderLine2"
			 />
	</view>
</template>

<script>
	import * as echarts from '../libs/echarts/echarts.min.js'; /*chart.min.js为在线定制*/
	import mpvueEcharts from '../components/mpvue-echarts/echarts.vue';
	export default {
		components: {
			mpvueEcharts
		},
		data() {
			return {
				loading: true,
			}
		},
		methods: {
			renderLine(e) {
				let {
					canvas,
					width,
					height
				} = e;
				echarts.setCanvasCreator(() => canvas);
				const chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chart);
				var options = {
					title: {
						text: '保健时长',
						textStyle: {
							fontSize: 10,
						},
					},
					grid: {
						containLabel: true
					},
					xAxis: {
						type: 'category',
						boundaryGap: true,
						axisLabel: {
							fontWeight: 600,
							color: '#333',
						},
						axisTick: {
							show: false,

						},
						axisLine: {
							lineStyle: {
								color: '#f2f3f2',
								width: 2,
							},

						}
					},
					yAxis: {
						type: 'value',
						name: '(min)',
						nameTextStyle: {
							fontWeight: 'bolder',
							color: '#333'
						},
						min: 0,
						max: 60,
						show: true,
						axisLine: {
							show: true,
							lineStyle: {
								color: '#f2f3f2',
								width: 2,
							}
						},
						axisLabel: {
							color: '#666',
							showMinLabel: false,

						},
						splitLine: {
							show: false
						},
					},
					series: [{
						type: 'line',
						//smooth: true,
						symbol: 'none',
						lineStyle: {
							color: '#0E9CFF',
							// width: 5
						},

						data: [
							['1st', 30],
							['2nd', 60],
							['3rd', 23],
							['4th', 45],
							['5th', 15],
							['6th', 50],
							['7th', 25],
						]
					}]
				};
				//初始化echarts实例
				chart.setOption(options);
			},
			renderLine2(e) {
				let {
					canvas,
					width,
					height
				} = e;
				echarts.setCanvasCreator(() => canvas);
				const chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chart);
				var options = {
					title: {
						text: '健康状态',
						textStyle: {
							fontSize: 10,
						},
					},
					grid: {
						containLabel: true,
						bottom: 25,
					},
					radar: {
						indicator: [{
								name: '精神',
								max: 100,
								colr: '#333'
							},
							{
								name: '机能',
								max: 100,
								colr: '#333'
							},
							{
								name: '运动',
								max: 100,
								colr: '#333'
							},
							{
								name: '心理',
								max: 100,
								colr: '#333'
							},
							{
								name: '体质',
								max: 100,
								colr: '#333'
							},

						]
					},
					series: [{
						name: '健康状态',
						type: 'radar',
						data: [{
								value: [50, 70, 30, 40, 50],
								symbol: 'none',

							},
						]
					}]
				};
				//初始化echarts实例
				chart.setOption(options);
			}
		}
	}
</script>

<style lang="scss">
	.me-healthData {
		>.line {
			margin: 40rpx 0;
			text-align: center;

			>text {
				font-size:24rpx !important;
				// position:relative;
				// top:-50rpx;
			}
		}
	}
</style>

结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值