1. 程式人生 > 實用技巧 >小程式如何在不同裝置上自適應生成海報

小程式如何在不同裝置上自適應生成海報

小程式canvas的API並沒有像其他的一樣支援小程式獨有的 rpx 自適應尺寸單位,在繪製內容時所應用的單位仍然是 px,那麼如何實現不同尺寸螢幕的自適應呢?

我們的在開發中常用的參考螢幕尺寸(iPhone6)為:375*667;

那麼想要適應其他尺寸的螢幕時只需按照iPhone6的繪製大小按比例進行換算即可:

獲取系統螢幕尺寸

先利用wx.getSystemInfo (獲取系統資訊)的API獲取螢幕寬度,然後除iPhone6的螢幕寬度,即可得到相對單位

// 在onLoad中呼叫
const that = this
wx.getSystemInfo({
  success: function (res) {
    console.log(res)
    that.setData({
      model: res.model,
      screen_width: res.windowWidth/375,
      screen_height: res.windowHeight
    })
  }
})

在繪製方法中將引數乘以相對單位即可實現自適應
這裡的rpx是相對不同螢幕寬度的相對單位,測量出得實際寬度,就是實際測出的px畫素值*rpx就可以了;之後無論實在iPhone5,iPhone6,iPhone7...都可以進行自適應。

這裡的html也要動態的設定寬和高

<canvas canvas-id="PosterCanvas" style="width:{{screen_width*375+'px'}}; height:{{screen_height*1.21+'px'}}"></canvas>
drawPoster(){
    let ctx = wx.createCanvasContext('PosterCanvas'),that=this.data;
    console.log('手機型號' + that.model,'寬'+that.screen_width*375,'高'+ that.screen_height)
    let rpx = that.screen_width
    //這裡的rpx是相對不同螢幕寬度的相對單位,實際的寬度測量,就是實際測出的px畫素值*rpx就可以了;之後無論實在iPhone5,iPhone6,iPhone7...都可以進行自適應。
    ctx.setFillStyle('#1A1A1A')
    ctx.fillRect(0, 0, rpx * 375, that.screen_height * 1.21)
    ctx.fillStyle = "#E8CDAA";
    ctx.setFontSize(29*rpx)
    ctx.font = 'normal 400  Source Han Sans CN';
    ctx.fillText('Hi 朋友', 133*rpx,66*rpx)
    ctx.fillText('先領禮品再買車', 84*rpx, 119*rpx)
    ctx.drawImage('../../img/sell_index5.png', 26*rpx, 185*rpx, 324*rpx, 314*rpx)
    ctx.drawImage('../../img/post_car2x.png', 66 * rpx, 222 * rpx, 243 * rpx, 145 * rpx)
    ctx.setFontSize(16*rpx)
    ctx.font = 'normal 400 Source Han Sans CN';
    ctx.fillText('長按掃描獲取更多優惠', 108*rpx, 545*rpx)
    ctx.drawImage('../../img/code_icon2x.png', 68 * rpx, 575 * rpx, 79 * rpx, 79 * rpx)
    ctx.drawImage('../../img/code2_icon2x.png', 229 * rpx, 575 * rpx, 79 * rpx, 79 * rpx)
    ctx.setStrokeStyle('#666666')
    ctx.setLineWidth(1*rpx)
    ctx.lineTo(187*rpx,602*rpx)
    ctx.lineTo(187*rpx, 630*rpx)
    ctx.stroke()
    ctx.fillStyle = "#fff"
    ctx.setFontSize(13 * rpx)
    ctx.fillText('xxx科技汽車銷售公司', 119 * rpx, 663 * rpx)
    ctx.fillStyle = "#666666"
    ctx.fillText('朝陽區·望京xxx科技大廈', 109 * rpx, 689 * rpx)
    ctx.setFillStyle('#fff')
    ctx.draw()
  },

如果圖片是線上地址 ctx.drawImage()會出錯,不能畫出圖片
因為會訪問一個get請求,是一個非同步操作,還沒等到get返回就執行了tx.draw()繪製畫布。 解決方案 就只在 wx.downloadFile()中成功下載了圖片在進行繪製畫布。

wx.downloadFile({
  url: that.data.url,
  success(res) {
    if (res.statusCode === 200) {
      // 活動
      ctx.drawImage(res.tempFilePath, 66 * rpx, 222 * rpx, 243 * rpx, 145 * rpx)
      // 二維碼
      ctx.draw()
    }
  }
})

儲存到相簿

很簡單就是在畫完圖片之後的draw回撥函式裡呼叫canvasToTempFilePath()生產一個零時記憶體裡的連結,然後在呼叫saveImageToPhotosAlbum()就可以了;其中牽扯到授權,如果你第一次拒絕了授權,你第二次進入的時候在iphone手機上是不會再次提醒你授權的,這時就需要你手動呼叫了;以下附上程式碼!

PPT模板下載大全https://www.wode007.com

ctx.draw(true, ()=>{
    // console.log('畫完了')
    wx.canvasToTempFilePath()({
      x: 0,
      y: 0,
      width: rpx * 375,
      height: that.screen_height * 1.21,
      canvasId: 'PosterCanvas',
      success: function (res) {
        // console.log(res.tempFilePath);
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: (res) => {
            console.log(res)
          },
          fail: (err) => { }
        })
      }
    }) 
  })

拒絕授權後再次提醒授權的程式碼

mpvue.saveImageToPhotosAlbum({

    filePath: __path,
    success(res) {
      mpvue.showToast({
      title: '儲存成功',
      icon: 'success',
      duration: 800,
      mask:true
      });
     },
    fail(res) {
        if (res.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || res.errMsg === "saveImageToPhotosAlbum:fail auth deny" || res.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {

      mpvue.showModal({
            title: '提示',
            content: '需要您授權儲存相簿',
            showCancel: false,
            success:modalSuccess=>{
              mpvue.openSetting({
                success(settingdata) {
                  // console.log("settingdata", settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    mpvue.showModal({
                      title: '提示',
                      content: '獲取許可權成功,再次點選圖片即可儲存',
                      showCancel: false,
                    })
                  } else {
                    mpvue.showModal({
                      title: '提示',
                      content: '獲取許可權失敗,將無法儲存到相簿哦~',
                      showCancel: false,
                    })
                  }
                },
                fail(failData) {
                  console.log("failData",failData)
                },
                complete(finishData) {
                  console.log("finishData", finishData)
                }
              })
            }
          })
      }
     }
  });

至此就算完了