9:41 ▮▮▮ 5G
移动端编程性能优化宝典DEVICE · 移动端开发
M 移动端编程性能优化宝典 Mobile Dev
#3421211 集成 2026.12.03 —

支付宝小程序集成Echarts图表 微信的ecCanvas组件直接搬会报错 从安装依赖到canvas渲染完整实操与常见坑排查

分类
集成
编号
3421211
发布
12.03
更新
12.03

支付宝小程序集成 ECharts,最忌讳的就是把微信的 ec-canvas 组件原封不动拷过来——几乎必然报错。根本原因只有一个:微信和支付宝是两套宿主环境,JSAPI 前缀一个是 wx 一个是 my,canvas 的取节点方式、旧版 API、事件对象都有差异,组件里的代码、运行时环境全对不上。下面这套实操是我实际踩坑后整理的:从装依赖、写组件、到 canvas 渲染出图,再附一份常见坑排查清单,照着做基本一遍跑通。

微信的 ec-canvas 为什么直接搬过来必报错?

先说清楚 ec-canvas 是什么:ec-canvas 是 ECharts 官方为微信小程序提供的封装组件,内部负责拿到 canvas 节点、调用 echarts.init 初始化图表,并把触摸事件转交给图表内部处理。它从诞生起就只面向微信环境,直接搬到支付宝小程序会踩三个硬差异:

  1. 全局对象不存在。组件里到处是 wx.getSystemInfoSync()、wx.createSelectorQuery(),支付宝里运行直接抛 wx is not defined,这是最直白的第一道报错。
  2. 文件后缀不被识别。微信的 .wxml / .wxss 在支付宝里必须改成 .axml / .acss,不改根本不会被当作组件模板加载。
  3. 旧版 canvas API 不兼容。微信 ec-canvas 为了兼容老基础库,走过 wx.createCanvasContext 的老路径;支付宝的老 API 返回的是一个代理上下文对象,不是真正的 canvas 节点,echarts.init 拿到它根本没法渲染。所以在支付宝上,唯一靠谱的路是 Canvas 2D:先通过 selector query 拿到 canvas 节点,再交给 echarts。

顺带说一句,如果你在 npm 上看到 lime-echart 这类多端图表组件,它对支付宝有专门适配,不想自己维护组件的话可以直接用它;但自己改一版 ec-canvas 也就百来行代码,可控性更高。

动手之前:环境和依赖怎么准备

基础库和开发者工具

Canvas 2D 需要较新的支付宝客户端和基础库版本,老版本上 selector query 的 fields({node: true}) 会返回空节点,这是后面“画布空白”问题的头号原因。动手前确认两件事:

  • 开发者工具升级到近一年的稳定版,模拟器里跑一下官方 Canvas 2D 示例;
  • 真机预览也测一次——支付宝的模拟器和真机渲染差异不小,只在模拟器里验证不可靠。

echarts 版本和体积怎么选

建议用 5.x 版本。拿 echarts-for-weixin 仓库里那份定制过的 echarts.min.js 最省事,它砍掉了对 DOM 环境的依赖,小程序里能直接用;如果想更瘦,用 echarts 5 的模块化入口按需引入:

import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([BarChart, LineChart, PieChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer])

体积差距很实际:完整版 echarts.min.js 是 MB 量级,支付宝主包上限只有 2MB,光一个图表文件就吃掉一半空间;按需构建之后通常能压到几百 KB 以内,取决于你用了多少图表类型。页面多的项目建议把 echarts 放分包,或干脆每个分包放一份裁剪过的构建。

目录结构

components/
  ec-canvas/
    index.js        // 组件逻辑
    index.json      // 组件配置
    index.axml      // 组件模板(微信的 index.wxml 改名而来)
    index.acss      // 组件样式
    echarts.min.js  // echarts 构建产物
pages/
  demo/
    index.js / index.axml / index.json / index.acss

方案一:把 ec-canvas 改造成支付宝版

核心改动就一句话:删掉兼容老 canvas 的分支,只保留 Canvas 2D 路径,把 wx. 全部换成 my.。下面是完整可跑的组件代码。

组件代码:index.js

const echarts = require('./echarts.min.js')

Component({
  properties: {
    canvasId: { type: String, value: 'ec-canvas' },
    ec: { type: Object, value: null } // 传 { option: {...} },图表配置放这里
  },

  lifetimes: {
    ready() {
      if (this.data.ec) this.init()
    }
  },

  methods: {
    init(callback) {
      const query = this.createSelectorQuery()
      query.select('#' + this.properties.canvasId)
        .fields({ node: true, size: true })
        .exec((res) => {
          if (!res || !res[0] || !res[0].node) {
            console.error('[ec-canvas] canvas 节点获取失败,检查 id 和 type="2d"')
            return
          }
          const canvasNode = res[0].node
          const sys = my.getSystemInfoSync()

          const chart = echarts.init(canvasNode, null, {
            width: res[0].width,
            height: res[0].height,
            devicePixelRatio: sys.pixelRatio
          })

          if (this.data.ec && this.data.ec.option) {
            chart.setOption(this.data.ec.option)
          }
          if (typeof callback === 'function') callback(chart)
          this.chart = chart
        })
    },

    touchStart(e) {
      if (this.chart && e.touches.length > 0) {
        const t = e.touches[0]
        const handler = this.chart.getZr().handler
        handler.dispatch('mousedown', { zrX: t.x, zrY: t.y })
        handler.dispatch('mousemove', { zrX: t.x, zrY: t.y })
      }
    },

    touchMove(e) {
      if (this.chart && e.touches.length > 0) {
        const t = e.touches[0]
        this.chart.getZr().handler.dispatch('mousemove', { zrX: t.x, zrY: t.y })
      }
    },

    touchEnd() {
      if (this.chart) {
        this.chart.getZr().handler.dispatch('mouseup', {})
      }
    },

    canvasToTempFilePath(opt) {
      const query = this.createSelectorQuery()
      query.select('#' + this.properties.canvasId)
        .fields({ node: true, size: true })
        .exec((res) => {
          if (res && res[0] && res[0].node) {
            opt.canvas = res[0].node
            my.canvasToTempFilePath(opt)
          }
        })
    }
  }
})

组件模板:index.axml 和 index.json

<!-- index.axml -->
<canvas id="{{canvasId}}" type="2d" class="ec-canvas"
  bindtouchstart="touchStart"
  bindtouchmove="touchMove"
  bindtouchend="touchEnd"></canvas>
// index.json
{ "component": true }
/* index.acss */
.ec-canvas { width: 100%; height: 100%; }

注意 type="2d" 是 Canvas 2D 的开关,去掉它 selector query 就取不到 node;这是从微信版照抄时最容易漏的一处——微信老版本组件里它是条件渲染的,支付宝版必须写死。

页面里怎么用

<!-- pages/demo/index.axml -->
<view class="chart-wrap">
  <ec-canvas id="mychart" canvas-id="mychart" ec="{{ ec }}"></ec-canvas>
</view>
/* pages/demo/index.acss */
.chart-wrap { width: 750rpx; height: 500rpx; }
// pages/demo/index.js
Page({
  data: {
    ec: {
      option: {
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: ['Q1', 'Q2', 'Q3', 'Q4'] },
        yAxis: { type: 'value' },
        series: [{ name: '销量', type: 'bar', data: [120, 200, 150, 80] }]
      }
    }
  },

  onUnload() {
    const comp = this.selectComponent('#mychart')
    if (comp && comp.chart) comp.chart.dispose()
  }
})

页面 json 里注册组件:

{
  "usingComponents": {
    "ec-canvas": "/components/ec-canvas/index"
  }
}

几个关键点逐段说

  • echarts.init 的第三个参数传 devicePixelRatio:echarts 内部会自己把 canvas 物理像素放大 dpr 倍,你不需要手动 ctx.scale。如果哪天你想脱离 echarts 直接用 2d 上下文画东西,才需要自己处理缩放。
  • option 通过 property 传而不是传函数:微信版习惯传 ec.onInit 初始化函数,但小程序的组件数据传递存在序列化,部分基础库和真机上函数会被丢掉,表现就是图表出来了但回调没执行、option 为 undefined。把配置对象传进来、初始化逻辑放组件里,是支付宝上最稳的写法。
  • 触摸事件靠 getZr().handler.dispatch 转发:echarts 监听的是 mousedown/mousemove/mouseup,小程序只给 touch 事件,所以要手动翻译一遍坐标。t.x / t.y 是相对 canvas 的坐标,拿不到的情况下面排查清单里讲。
  • lifetimes 不兼容的老基础库:把 ready 直接提到 Component 顶层即可,逻辑不变。

方案二:不写组件,页面里直接初始化

只有一两个图表、不需要复用时,这个方案更直接。在页面 onReady 里拿节点、初始化:

const echarts = require('/components/ec-canvas/echarts.min.js')

Page({
  onReady() {
    const query = my.createSelectorQuery()
    query.select('#echart')
      .fields({ node: true, size: true })
      .exec((res) => {
        if (!res || !res[0] || !res[0].node) return
        const canvas = res[0].node
        const sys = my.getSystemInfoSync()

        this.chart = echarts.init(canvas, null, {
          width: res[0].width,
          height: res[0].height,
          devicePixelRatio: sys.pixelRatio
        })
        this.chart.setOption({
          series: [{ type: 'pie', radius: '60%', data: [
            { value: 1048, name: '搜索' },
            { value: 735, name: '直接' }
          ]}]
        })
      })
  },

  onUnload() {
    if (this.chart) this.chart.dispose()
  }
})

对应的 axml 就是一行:

<canvas id="echart" type="2d" style="width: 100%; height: 400px;"></canvas>

代价是触摸联动(tooltip 跟随手指)得自己在页面里写 dispatch;或者干脆关掉 tooltip、用静态图表换取零成本。图表多、页面杂的项目还是老老实实用组件方案。

图表空白、tooltip 不跟手?按这个清单排查

画布一片空白

按出现概率从高到低查:

  1. 没写 type="2d",或基础库太老取不到 node——先在回调里打印 res[0].node,是 null 就是这个问题;
  2. canvas 没有显式宽高。父容器用了 height: 100% 但自己的高度也是百分比链,最终解析成 0,echarts 拿到 width=0 画了个寂寞。给 canvas 或父容器一个确定的 px/rpx 高度;
  3. 初始化时机早于渲染。onReady 里节点还没挂载完,exec 回调拿不到尺寸,把初始化挪到 onReady 末尾或下一个 tick;
  4. option 没传进来。对照上面说的函数序列化问题,打印一下 this.data.ec.option。

触摸联动失效

先确认 canvas 上绑了三个 touch 事件且组件里方法名拼对;再打印 e.touches[0],看有没有 x/y 字段。个别基础版本只给 clientX/clientY,这时先用 selector query 拿 canvas 的 rect(fields({rect: true})),用 clientX - rect.left 换算出相对坐标再 dispatch。

图表能显示但动画卡顿

多半是 echarts 构建产物没裁剪干净,或者设备性能弱。可以先关掉动画验证:animation: false,如果立刻流畅,说明是渲染压力问题——减少数据点数、关闭阴影和渐变,或换按需构建的轻量包。

容器尺寸变化后图表不变形

小程序没有窗口 resize 事件,横屏、页面跳转回来、容器折叠后图表不会自适应。要手动处理:重新 query 尺寸,调用 chart.resize({ width, height }),必要时 dispose 后重建。

包体积超限

三个手段叠加用:按需构建 echarts(只留用到的图表和组件)、图表相关页面整体挪进分包、把 echarts.min.js 单独放一个公共分包按需加载。完整版和裁剪版体积差着几倍,超限基本都是没裁剪导致的。

常见问题

必须改组件吗,能直接用官方微信版吗?

不能直接用。wx is not defined 只是第一层报错,就算把 wx 全局变量 hack 掉,旧版 canvas 路径在支付宝上也走不通。改造成本很低(删兼容分支、换 my.),或者直接用支持支付宝的多端图表组件。

支付宝老版本客户端支持 Canvas 2D 吗?

不支持或支持不完整。表现为 fields({node: true}) 返回的 node 为空、画布空白。解法是升级支付宝客户端和基础库,没有绕过的必要——老 API 那条路 echarts 根本没法用。

tooltip 出来了但不跟手?

触摸坐标的问题,不是图表配置的问题。打印 e.touches[0] 确认 x/y 存在;不存在就用 canvas 的 rect 做 clientX - left 换算,再 dispatch 给 chart.getZr().handler。

echarts 版本选哪个?

选 5.x,并且优先用裁剪过的构建产物。4.x 的老构建对小程序环境适配差,5.x 的模块化入口可以精确控制打包内容,体积和兼容性都更好。

一个页面放多个图表要注意什么?

每个 ec-canvas 的 canvas-id 必须唯一,初始化用 lazyLoad 模式:页面传 ec: {},在数据准备好后逐个 this.selectComponent('#id').init() 主动触发,避免一次性初始化把首屏拖慢。

同

同分类条目

same