微信小程序生成指定頁面小程序碼海報圖片分享思路總結

  本博客主要說下思路,具體代碼不貼html

一、考慮到組件複用,因此我把它作成一個自定義的組件canvas

<my-poster id="getPoster" avater="{{imageUrl}}" knowledges="{{klPoster}}" scene="{{topicId}}">
</my-poster>

  能夠傳圖片avater、文字內容knowledges、頁面參數scene小程序

二、組件裏面首先是得須要一個畫布。微信

  畫布外能夠正常寫元素標籤,定義樣式網絡

<view class="mask_screen" wx:if="{{showpost}}">
  <view class='poster_box'>
    <view class='poster_content' id='canvas-container'>
      <canvas canvas-id="myCanvas" style="width:100%;height:{{canvasHeight}}px;" />
    </view>
    <view class='tips'>保存圖片,分享給小夥伴吧</view>
    <view class='save' bindtap='saveShareImg'>
      <image class='down' mode='widthFix' src='../../assets/dbs/down.png'></image>
      <text>保存</text>
    </view>
    <image class='close'  bindtap='closePoste' mode='widthFix' src='../../assets/dbs/close.png'></image>
  </view>
</view>

三、畫布準備好以後,就是須要準備畫圖的一些資源,好比圖片之類的ide

  網絡圖片需利用微信接口 wx.downloadFile 下載下來以後,獲取圖片的臨時地址,根據該臨時地址才能夠畫圖;post

  若是是工程類圖片,只須要寫好路徑,便可以畫圖。好比:this

    // 網絡圖片
    if (topicImage) { wx.downloadFile({ url: topicImage, success: function(res) { wx.hideLoading(); if (res.statusCode === 200) { var productSrc = res.tempFilePath; that.calculateImg(productSrc, function(data) { that.getCode(productSrc, data) }) } } }) } // 工程內圖片
let dbicon = '../../assets/dbs/' + item.type + '.png'; ctx.drawImage(dbicon, 15, offsetHeight + 10, 10, 10)

四、有些圖片可能要計算寬高的,須要利用微信接口 wx.getImageInfo 獲取圖片寬高等信息,wx.getSystemInfo 獲取手機屏幕寬高等信息,根據比例去計算繪製url

//計算圖片尺寸
 calculateImg: function(src, cb) { var that = this; wx.getImageInfo({ src: src, success(res) { wx.getSystemInfo({ success(res2) { var ratio = res.width / res.height; var imgHeight = res2.windowWidth * 0.6 / ratio; // var screeRratio = res2.screenWidth / res2.screenHeight
 that.setData({ canvasHeight: imgHeight + 280
                // canvasHeight: res2.windowWidth * 0.5 / screeRratio
 }) cb(imgHeight); } }) } }) }

五、再就是獲取頁面的小程序碼,微信文檔有介紹:三種接口獲取方式spa

  獲取小程序碼:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html

六、繪製文字換行問題,上一篇有介紹

七、圖片生成以後,保存圖片。主要利用微信接口 wx.canvasToTempFilePath 和 wx.saveImageToPhotosAlbum

//點擊保存到相冊
 saveShareImg: function() { var that = this; wx.showLoading({ title: '正在保存', mask: true, }) setTimeout(function() { wx.canvasToTempFilePath({ canvasId: 'myCanvas', success: function(res) { wx.hideLoading(); var tempFilePath = res.tempFilePath; wx.saveImageToPhotosAlbum({ filePath: tempFilePath, success(res) { wx.showModal({ content: '圖片已保存到相冊,趕忙曬一下吧~', showCancel: false, confirmText: '好的', confirmColor: '#333', success: function(res) { that.closePoste(); if (res.confirm) {} }, fail: function(res) { console.log(res) } }) }, fail: function(res) { wx.showToast({ title: res.errMsg, icon: 'none', duration: 2000 }) } }) }, fail: function(err) { console.log(err) } }, that); }, 1000); },

八、注意事項:

(1)圖片要提早下載:這裏面有一個問題就是,圖片要提早下載完以後再繪圖,否則圖片顯示不出來,能夠把下載圖片的方法單獨拎出來,而後下載圖片後回調繪圖方法。

(2)ctx.draw(),這個方法是在繪製完成以後在調用,否則容易其它被覆蓋。

  大體思路就是如此。

相關文章
相關標籤/搜索