1. 程式人生 > 其它 >微信小程式canvas元件層級最高覆蓋其他元素的解決方法

微信小程式canvas元件層級最高覆蓋其他元素的解決方法

技術標籤:小程式小程式

問題描述

小程式中引入echarts官方元件,發現繪製出的圖形總是處於頁面最上層,在需要使用時間選擇器時影響了picker-view的展示,需要移到下層。

嘗試方法

1.z-index

ec-canvas圖形元件設定position並設定z-index:0,時間選擇器設定position和z-index:1,沒有效果。

2.用svg渲染

小程式不支援,echarts官方只有canvas版本的元件

原因分析

微信官方文件中看到這樣的提示:

最終解決

想法來源:https://github.com/ecomfe/echarts-for-weixin/issues/734

思路是點選上方選擇器時呼叫wx.canvasToTempFilePath函式將canvas元件轉化成一張圖片儲存在臨時資料夾中,然後通過setData將canvas元件隱藏,將圖片顯示出來。

程式碼實現

detailComponent.wxml頁面:

    <view class="price-chart">
      <ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ec}}" style="{{hideCanvas?'position:fixed;left:100%':''}}"></ec-canvas>
      <image class="canvas-image" src="{{canvasImage}}" alt=""></image>
    </view>

detailComponent.js中點選選擇器的處理函式:

const ec_component=this.echartComponent;
    ec_component.canvasToTempFilePath({
      success:res => {
        console.log('drawSuccess',res.tempFilePath);
          this.setData({
            hideCanvas:true,
            canvasImage:res.tempFilePath,
          })
      },
      fail: res => console.log('失敗',res)
    })

ec-canvas.js中的canvasToTempFilePath函式:

    canvasToTempFilePath(opt) {//引數是回撥函式,包含成功和失敗兩種情況
      if (this.data.isUseNewCanvas) {
        // 新版
        const query = wx.createSelectorQuery().in(this)
        query
          .select('.ec-canvas')
          .fields({ node: true, size: true })//fields返回的是nodesref對應的selectorQuery
          .exec(res => {
            const canvasNode = res[0].node
            opt.canvas = canvasNode
            wx.canvasToTempFilePath(opt)
          })
      } else {
        // 舊的
        if (!opt.canvasId) {
          opt.canvasId = this.data.canvasId;
        }
        ctx.draw(true, () => {
          wx.canvasToTempFilePath(opt, this);
        });
      }
    },

最後在隱藏tab的時候再把canvas元件還原回來。

這種方法的缺點是用圖片替換圖形元件時會螢幕會明顯的閃一下,需要找使用者體驗更好的方法。