小程序echarts+canvasdrawer實現頁面轉化圖片

//業務層代碼
let that = this
    // 保存圖片到臨時的本地文件
    //注意chart初始化實例不能輸出圖片
    const ecComponent = this.selectComponent('#mychart-dom-graph');//獲取echarts組件
    ecComponent.canvasToTempFilePath({
    //安卓機型此處不會成功回調
      success: res => {
        that.eventDraw(res.tempFilePath)
      },
      fail: res => console.log('失敗', res)
});

//ec-canvas.js源碼
canvasToTempFilePath(opt) {
      if (!opt.canvasId) {
        opt.canvasId = this.data.canvasId;
      }
      const system = wx.getSystemInfoSync().system
      ctx.draw(true, () => {//此處微信api在安卓部分機型不會回調 ,相反ctx.draw(false)清空畫布會執行,導致echarts已經繪製畫布清空,輸出爲空圖片         
          wx.canvasToTempFilePath(opt, this);
      });  
    }
//修改後
canvasToTempFilePath(opt) {
      if (!opt.canvasId) {
        opt.canvasId = this.data.canvasId;
      }
      const system = wx.getSystemInfoSync().system
      if (/ios/i.test(system)) {
        ctx.draw(true, () => {          
          wx.canvasToTempFilePath(opt, this);          
        });  
      } else {//針對安卓機型異步獲取已繪製圖層
      ctx.draw(true,()=>{
        //斷點打印依舊不會執行setTimeout(() => {wx.canvasToTempFilePath(opt, this);}, 1000);}});
        ctx.draw(true);
        setTimeout(() => {//延遲獲取
          wx.canvasToTempFilePath(opt, this);
        }, 1000);
      }
    },

onReady動態修改echarts[options]失敗 

 onReady: function() {
    let that = this;
    setTimeout(() => {//異步解決echarts實例沒有加載成功的無法設置options
      option.series[0].data[0].value = that.data.canvasListData
      chart.setOption(option);
    }, 500);
  }
<!--備註-->
//提前聲明變量
let chart = null;
var option = {}

3.網絡圖片需下載到本地,注意配置downloadFile合法域名,尤其是微信頭像鏈接

4.相冊授權拒絕後,button不會再次彈出授權彈窗,openSetting強制打開設置開啓授權。

5.圓形頭像建議切鏤空圖覆蓋,rect,clip有bug很難實現UI效果

建議查看:微信小程序社區的帖子。

6.cancvas要畫2倍圖,否則輸出圖片模糊

小程序繪製圓形頭像框  

小程序繪製圓形頭像框  
ctx.save()
    ctx.beginPath()
    //首先繪製一個圓形的弧線,大小位置根據你的需求而定,也就是說你想讓它放在什麼位置,就讓它放在什麼位置
    ctx.arc(width / 8, height / 3 + 0.10 * width + 20, 0.10 * width, 0, 2 * Math.PI)
    // //這塊我是用獲取到的width和height來確定頭像的位置
    ctx.setStrokeStyle('#000')
    ctx.stroke()
    //使用clip() 方法從原始畫布中剪切任意形狀和尺寸。一旦剪切了某個區域,則所有之後的繪圖都會被限制在被剪切的區域內
    ctx.clip()
    ctx.drawImage(imgPath, width / 8 - 0.10 * width, height / 3 + 20, 0.20 * width, 0.20 * width)
    ctx.restore()

原文地址 :  https://segmentfault.com/a/1190000017503185 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章