uniapp 微信小程序使用echarts

这篇具有很好参考价值的文章主要介绍了uniapp 微信小程序使用echarts。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本文目的:通过分包的方式,尽可能在微信小程序中使用最新的echarts。
当然你也可以直接使用现成的uchart或者市场里别人封好的echarts.

  • 准备工作
    • 下载echarts-for-weixin源码。
      • 复制ec-canvas文件夹以及下属文件,在uniapp项目中与pages同级的地方创建wxcomponents文件夹,将复制的文件夹放于该文件夹下。wxcomponents文件名不可更改,参考:Uniapp小程序自定义组件支持
      • 修改pages.json文件,往globalStyle中添加"usingComponents": {"ec-canvas": "/wxcomponents/ec-canvas/ec-canvas"}
      • 跑一下项目,这样会在ec-canvas下生成一个ec-canvas.vue,我自己试过来跑在浏览器上(h5)会生成,直接跑微信小程序不会生成。
      • ec-canvas下已经包含echarts文件,但版本可能不是最新的,想换新的可以去echarts github下载,至此准备工作完成。
  • 修改ec-canvas.vue中的代码
    • 替换两个canvas标签中所绑定的事件,视methods中的方法名而定
      • @touchstart=“touchStart”
      • @touchmove=“touchMove”
      • @touchend=“touchEnd”
    • 去除import上的两行代码:global['__wxVueOptions'] = {components:{}}global['__wxRoute'] = 'ec-canvas/ec-canvas'
    • 确保echart.js文件的路径与名称是否引用正确,下载过来没改名可能是echarts.min.js
    • export default global['__wxComponents']['ec-canvas/ec-canvas']改为export default {},然后将Component中的键按Vue的原本语法一一复制:
      • properties => props, 其中的value改为default
      • data => data() { return {} }
      • ready => mounted() {}
      • methods => 直接复制即可
      • compareVersion和wrapTouch这两个方法至于export default上即可,无需放在methods中
    • 给methods的init方法加上async,在if (isUseNewCanvas)上加上await this.$nextTick(),否则具体的init方法中获取node会变成null。
    • 在当前文件搜索this.data替换为this.
    • 在当前文件搜索setData,将唯一一条this.setData({ isUseNewCanvas })改为this.isUseNewCanvas = isUseNewCanvas
    • 改完后的ec-canvas.vue参考:
<template>
  <uni-shadow-root class="ec-canvas-ec-canvas">
    <canvas
      v-if="isUseNewCanvas"
      type="2d"
      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>
  </uni-shadow-root>
</template>

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

let ctx

function 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
}

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,
      value: 'ec-canvas',
    },

    ec: {
      type: Object,
    },

    forceUseOldCanvas: {
      type: Boolean,
      value: false,
    },
  },
  data() {
    return {
      isUseNewCanvas: false,
    }
  },
  onReady: function () {
    // Disable prograssive because drawImage doesn't support DOM as parameter
    // See https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.drawImage.html
    echarts.registerPreprocessor((option) => {
      if (option && option.series) {
        if (option.series.length > 0) {
          option.series.forEach((series) => {
            series.progressive = 0
          })
        } else if (typeof option.series === 'object') {
          option.series.progressive = 0
        }
      }
    })

    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: {
    init: async function (callback) {
      const version = wx.getSystemInfoSync().SDKVersion

      const canUseNewCanvas = compareVersion(version, '2.9.0') >= 0
      const forceUseOldCanvas = this.forceUseOldCanvas
      const isUseNewCanvas = canUseNewCanvas && !forceUseOldCanvas
      this.isUseNewCanvas = isUseNewCanvas

      if (forceUseOldCanvas && canUseNewCanvas) {
        console.warn('开发者强制使用旧canvas,建议关闭')
      }
      await this.$nextTick()
      if (isUseNewCanvas) {
        // console.log('微信基础库版本大于2.9.0,开始使用<canvas type="2d"/>');
        // 2.9.0 可以使用 <canvas type="2d"></canvas>
        this.initByNewWay(callback)
      } else {
        const isValid = 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)

      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') {
            this.chart = callback(canvas, res.width, res.height, canvasDpr)
          } else if (
            this.ec &&
            typeof this.ec.onInit === 'function'
          ) {
            this.chart = this.ec.onInit(
              canvas,
              res.width,
              res.height,
              canvasDpr
            )
          } else {
            this.triggerEvent('init', {
              canvas: canvas,
              width: res.width,
              height: res.height,
              canvasDpr: canvasDpr, // 增加了dpr,可方便外面echarts.init
            })
          }
        })
        .exec()
    },

    initByNewWay(callback) {
      // 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
          this.canvasNode = canvasNode

          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, this.canvasId, true, canvasNode)
          echarts.setCanvasCreator(() => {
            return canvas
          })

          if (typeof callback === 'function') {
            this.chart = callback(canvas, canvasWidth, canvasHeight, canvasDpr)
          } else if (
            this.ec &&
            typeof this.ec.onInit === 'function'
          ) {
            this.chart = this.ec.onInit(
              canvas,
              canvasWidth,
              canvasHeight,
              canvasDpr
            )
          } else {
            this.triggerEvent('init', {
              canvas: canvas,
              width: canvasWidth,
              height: canvasHeight,
              dpr: canvasDpr,
            })
          }
        })
    },
    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.chart && e.touches.length > 0) {
        var touch = e.touches[0]
        var handler = this.chart.getZr().handler
        handler.dispatch('mousedown', {
          zrX: touch.x,
          zrY: touch.y,
          preventDefault: () => {},
          stopImmediatePropagation: () => {},
          stopPropagation: () => {},
        })
        handler.dispatch('mousemove', {
          zrX: touch.x,
          zrY: touch.y,
          preventDefault: () => {},
          stopImmediatePropagation: () => {},
          stopPropagation: () => {},
        })
        handler.processGesture(wrapTouch(e), 'start')
      }
    },

    touchMove(e) {
      if (this.chart && e.touches.length > 0) {
        var touch = e.touches[0]
        var handler = this.chart.getZr().handler
        handler.dispatch('mousemove', {
          zrX: touch.x,
          zrY: touch.y,
          preventDefault: () => {},
          stopImmediatePropagation: () => {},
          stopPropagation: () => {},
        })
        handler.processGesture(wrapTouch(e), 'change')
      }
    },

    touchEnd(e) {
      if (this.chart) {
        const touch = e.changedTouches ? e.changedTouches[0] : {}
        var handler = this.chart.getZr().handler
        handler.dispatch('mouseup', {
          zrX: touch.x,
          zrY: touch.y,
          preventDefault: () => {},
          stopImmediatePropagation: () => {},
          stopPropagation: () => {},
        })
        handler.dispatch('click', {
          zrX: touch.x,
          zrY: touch.y,
          preventDefault: () => {},
          stopImmediatePropagation: () => {},
          stopPropagation: () => {},
        })
        handler.processGesture(wrapTouch(e), 'end')
      }
    },
  },
}
</script>
<style scoped>
.ec-canvas {
  width: 100%;
  height: 100%;
}
</style>


  • ec-canvas.vuewx-canvas.jsecharts.js复制到需要使用的分包中,三个文件需在同一目录下,再在组件中引用即可,注意引用组件与echarts的路径:
    • 复制完后,注意将wxcomponents 文件夹删除以及pages中对应的地方,否则主包体积会变大。
  • 示例
<template>
  <view style="height: 500rpx">
    <ec-canvas
      ref="canvasRef"
      style="height:100%;width:100%;"
      canvas-id="mychart-bar"
      :ec="{ onInit: initChart }"
    />
  </view>
</template>

<script>
import * as echarts from './components/echarts.min.js'
import EcCanvas from './components/ec-canvas'
let chartInstance
export default {
  components: {
    EcCanvas,
  },
  data() {
    return {}
  },
  mounted() {
    setTimeout(() => {
      this.setOption({
        series: [
          {
            data: [12, 20, 15, 8, 7, 11, 13],
            type: 'bar',
          },
        ],
      })
    },3000)
  },
  methods: {
    initChart(canvas, width, height, dpr) {
      chartInstance = echarts.init(canvas, null, {
        width,
        height,
        devicePixelRatio: dpr, // 像素
      })
      canvas.setChart(chartInstance)
      chartInstance.setOption({
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar',
          },
        ],
      })
      return chartInstance
    },
    // 需要更新图表数据时调用
    setOption(data) {
      if(!chartInstance) return
      chartInstance.setOption(data)
    }
  },
}
</script>

ec-canvas 进一步封装以及同时适配H5,参考我的下一篇文章:uniapp echarts 适配H5与微信小程序文章来源地址https://www.toymoban.com/news/detail-757399.html

到了这里,关于uniapp 微信小程序使用echarts的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【uniapp】微信小程序迁移至uniapp以及echarts图表

    需要对微信小程序开发和uniapp开发都有了解 目标: 微信小程序原生开发转为uni-app开发 微信小程序云开发转为uniCloud阿里云开发,涉及云数据库和云存储的迁移 迁移后依然发行至微信小程序 借助 miniprogram-to-uniapp 工具,源项目同级目录下会生成后缀为 _uni 的uniapp项目 微信云

    2024年02月09日
    浏览(42)
  • uniapp/微信小程序解决echarts层次问题

    1.由于原生的canvas组件高于其他组件 2.这样设置z-index没有用 3.大部门解决办法是将echarts转化成图片 看了微信小程序官方文档,官方提供了一种cover-view标签来覆盖canvas、video等层级过高问题   所以本次使用cover-view来解决层级问题一下 以下是代码实现: cover-view class=\\\"customerb

    2024年02月09日
    浏览(23)
  • uniapp echarts 适配H5与微信小程序

    接上文:uniapp 微信小程序使用echarts,这篇文章目的为使用uniapp时提供一个同时兼容H5和小程序的echarts组件,在使用时尽量减少心智负担。 首先修改uniapp 微信小程序使用echarts中的 ec-canvas 组件,将initChart方法置于该组件内部,而不是存在于业务组件中。 1.1 在 ec-canvas 组件m

    2024年02月06日
    浏览(33)
  • uniapp微信小程序接入echarts(踩坑无数)

    因为本次小程序开发使用到了echarts 发现接入有点麻烦,记录一下 使用了uniapp插件市场的 echarts-for-wx插件 导入到自己的项目会多出以下文件夹,真正有用的是红框内的三个文件,可以将其移入到components下,具体哪个页面/组件使用了就引入 这里我是把uni-ec-canvas移入到compone

    2024年02月12日
    浏览(31)
  • uniapp 微信小程序 echarts地图 点击显示类目

    效果如图: 在tooltip内axisPointer内添加 label:{show:true} 即可显示“请求离婚”的标题

    2024年02月13日
    浏览(31)
  • 【uniapp】中 微信小程序实现echarts图表组件的封装

     插件地址:echarts-for-uniapp - DCloud 插件市场 图例: 一、uniapp 安装   二、文件夹操作 将 node_modules 下的 uniapp-echarts 文件夹复制到 components 文件夹下  当前不操作此步骤的话,运行 - 运行到小程序模拟器 - 微信开发者工具 时,echarts图表显示不出来 原因:运行到小程序打包过

    2024年02月12日
    浏览(35)
  • uniapp微信小程序+echarts简单图表以及与后端交互

    效果图:   需要的两个主要文件就是  echarts.min.js   和  echarts.vue  1、 echarts.min.js 可以去官网定制 链接   ECharts 在线构建   或者直接去GitHub - Tawesome666/echarts: echarts 下载 (注意:我这个只有柱状图和折线图) 2、 echarts.vue  可以使用 Visual Studio Code  打开你的文件夹使用命

    2024年02月09日
    浏览(33)
  • 微信小程序使用echarts

    前期准备 : 1.echarts提供了一个微信小程序原生组件,下载地址:ecomfe/echarts-for-weixin ,拿到 ec-canvas 文件夹 2. 到 echarts官网 在线定制组件包 注意:版本一定要和 ec-canvas 相同 3.将下载的 echarts.min.js 替换掉原本的 echarts.js ,小程序文件过大影响发布 4.引入 ec-canvas.json ec-canvas

    2023年04月23日
    浏览(36)
  • 微信小程序中使用动态echarts

    解压后打开,把ec-canvas文件夹复制到项目pages同目录下 如有必要,将 ec-canvas 目录下的 echarts.js 替换为最新版的 ECharts。如果希望减小包体积大小,可以使用自定义构建生成并替换 echarts.js 进入官网echarts点击下载 然后根据自己的需求选择需要的图表、坐标系、组件进行打包下

    2024年02月14日
    浏览(30)
  • 微信小程序中使用echarts方法

    echarts是一个基于JS的数据可视化图标库,它提供了直观,生动,可交互,可个性定制的数据可视化图表。一般在vue中会使用到,并且官网也详细的说明了如何在vue中使用,但是今天我想来探讨的是,如何在 微信小程序中使用echarts : 1. ec-canvas的github仓库 官网中介绍到:echa

    2024年02月15日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包