微信小程序 canvas 生成圖片保存本地 并分享至朋友圈

微信小程序圖文分享功能。相信現(xiàn)在每個小程序都會有這個功能,用來推廣等。 最近也做了相關開發(fā)。這邊分享一下代碼。希望幫助到需要的小伙伴。(canvas里面商品名稱超過多少位 進行換行處理。有相同場景的 可以直接copy代碼)

image.png

自己無聊倒騰了小程序 歡迎大家測試使用~


gh_af88ca3ac9c4_430.jpg

1.畫布 canvas.wxml ()

1.bindlongpress: demo種長按canvs可以預判圖片和保存發(fā)送給朋友等。這是微信自帶的。 小伙伴可以看一眼也無妨。

   <cover-view>
   <canvas style="width:100%;height:{{contentHeight}}px" canvas-id="myCanvas" bindlongpress="savePic"> 
    <button bindtap='saveShareImg'>保存圖片</button>
    <button bindtap='savePic'>預覽并發(fā)送</button>
  </canvas>
  </cover-view>

2.繪制canvas 以及代碼邏輯(注意點在下方)

1.wx.getSystemInfo: 獲取設備信息。這邊就可以為canvas做大小適配。

2.wx.downloadFile({}): 很多小伙伴開發(fā)中,圖片路徑直接用后臺獲取的http鏈接作為路徑。這樣會有個問題、圖文分享第一次有圖片。但是第二遍再次打開則沒有圖片了。顯示空白問題。解決方案是使用 wx.downloadFile({}) 先將http的圖片下載下來,存在變量中。就可以避免了

3.wx.canvasToTempFilePath: 把當前畫布指定區(qū)域的內容導出生成指定大小的圖片。在 draw() 回調里調用該方法才能保證圖片導出成功。

上面注意點在下方代碼都有體現(xiàn),可以查看下位置。及如何使用。

//canvas.js
Page({
  data: {
    windowWidth: 0, //屏幕寬度
    windowHeight: 0,//屏幕高度
    contentHeight: 0,//內容高度
    thinkList: [], //文字超出換行處理
    lineHeight: 30, //固定值
    contentTitle: "iPhone XS Max(256GB) 金色 移動聯(lián)通電信4G手機 雙卡雙待", //商品標題
    price: "10999.00",//商品價格
    delPrice: "12999.00",//劃線價
    canvasUrl: "", //canvas李彪
    qrCode: "https://wanmi-b2b.oss-cn-shanghai.aliyuncs.com/201901310959076784.jpeg", //小程序碼https圖片路徑
    goodsInfoImg: "",  //商品圖片
    specText: "6.5英寸視網(wǎng)膜全面屏,面容ID" //規(guī)格
  },

  onLoad: function (options) {
    let that = this;
    //獲取設備信息高度。計算出其他的高度等
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
          normalPageX:
            res.windowWidth - (res.windowWidth + res.windowWidth * 0.72) / 2, //左邊文本圖片X軸位置
          boxWidth: res.windowWidth * 0.84, //分享圖片box寬度
          boxheight: res.windowWidth * (0.222 + 0.72 + 0.192) + 80, //分享圖片box高度
          boxPageY: res.windowWidth * 0.081, //boxY軸位置
          imgWidth: res.windowWidth * 0.77, //商品圖片寬度
          imgHeight: res.windowWidth * 0.92, //商品圖片高度
          imgPageY: res.windowWidth * 0.232, //商品圖片Y軸位置
          codeWidth: res.windowWidth * 0.192, //小程序碼圖片寬度
          codeHeight: res.windowWidth * 0.192, //小程序碼圖片高度
          codePageY: res.windowWidth * 0.222 + res.windowWidth * 0.72 + 40, //小程序碼Y軸位置
          avatarPageY: res.windowWidth * 0.222 + res.windowWidth * 0.72 + 15, //頭像Y軸位置
          titlePageY: res.windowWidth * 0.222 + res.windowWidth * 0.72 + 65, //標題Y軸位置
          specPageY: res.windowWidth * 0.222 + res.windowWidth * 0.72 + 82, //規(guī)格Y軸位置
          pricePageY: res.windowWidth * 0.222 + res.windowWidth * 0.72 + 123, //價格Y軸位置
          timePageY: res.windowWidth * 0.222 + res.windowWidth * 0.72 + 118 //秒殺Y軸位置
        });
      }
    });
    //網(wǎng)絡圖片轉為本地圖片,直接顯示網(wǎng)絡圖片的話真機不顯示
    that.getTempFile("http://img14.360buyimg.com/n0/jfs/t1/3730/7/3438/394579/5b996f2eE1727c59e/373cf10d42a53b72.jpg");
    // }
  },
  //臨時圖片路徑
  getTempFile: function (url) {
    wx.showLoading({
    });
    let that = this;
    wx.downloadFile({
      url: url,
      success: function (res) {
        console.log("res.tempFilePath===>", res.tempFilePath)
        that.setData({
          goodsInfoImg: res.tempFilePath
        });
        //繼續(xù)生成商品的小程序碼
        that.downloadSkuQrCode(that.data.qrCode);
      },
      fail: function (err) { }
    });
  },
  getData: function () {
    let that = this;

    let i = 0;
    let lineNum = 1;
    let thinkStr = "";
    let thinkList = [];
    for (let item of that.data.contentTitle) {
      if (item === "\n") {
        thinkList.push(thinkStr);
        thinkList.push("a");
        i = 0;
        thinkStr = "";
        lineNum += 1;
      } else if (i === 21) {
        thinkList.push(thinkStr);
        i = 1;
        thinkStr = item;
        lineNum += 1;
      } else {
        thinkStr += item;
        i += 1;
      }
    }
    thinkList.push(thinkStr);
    that.setData({
      thinkList: thinkList
    });
    that.createNewImg(lineNum);
  },

  //畫矩形,也是整塊畫布的大小,寬度是屏幕寬度,高度根據(jù)內容多少來動態(tài)設置。
  drawSquare: function (ctx, height) {
    let that = this;
    ctx.rect(
      that.data.windowWidth * 0.08,
      that.data.boxPageY,
      that.data.boxWidth,
      height
    );
    ctx.setFillStyle("#fff");
    ctx.fill();
  },

  // 設置文字大小,并填充顏色。
  drawFont: function (ctx, contentTitle, height) {
    let that = this;
    let str = that.data.contentTitle;
    let firstline;
    let secondline;
    //一行顯示14個字,超過一行時
    if (str.length > 23) {
      //第一行截取前14個字符
      firstline = str.substring(0, 23);
      //兩行都顯示不下
      if (str.length > 46) {
        secondline = str.substr(23, 23) + "...";
      } else {
        //第二行取剩下的
        secondline = str.substr(23, str.length - 23);
      }
    } else {
      //一行就能顯示時候
      firstline = str;
    }

    ctx.setFontSize(14);
    ctx.setFillStyle("#000");
    ctx.fillText(firstline, that.data.normalPageX, that.data.titlePageY);
    if (secondline) {
      ctx.setFontSize(12);
      ctx.setFillStyle("#333");
      ctx.fillText(
        secondline,
        that.data.normalPageX,
        that.data.titlePageY + 17
      );
    }
    if (that.data.specText) {
      ctx.setFontSize(12);
      ctx.setFillStyle("#999999");
      ctx.fillText(
        that.data.specText,
        that.data.normalPageX,
        that.data.specPageY + 18
      );
    }
  },
  // 根據(jù)文字多少動態(tài)計算高度,然后依次畫出矩形,文字,橫線和小程序碼。
  createNewImg: function (lineNum) {
    let that = this;
    let ctx = wx.createCanvasContext("myCanvas");
    let contentHeight = that.data.boxheight;
    that.drawSquare(ctx, contentHeight);
    that.setData({
      contentHeight: contentHeight
    });
    let height = 100;
    for (let item of that.data.thinkList) {
      if (item !== "a") {
        that.drawFont(ctx, item, height);
        height += that.data.lineHeight;
      }
    }
    //商品圖片
    ctx.drawImage(
      that.data.goodsInfoImg,
      that.data.normalPageX,
      that.data.imgPageY,
      that.data.imgWidth,
      that.data.imgWidth
    );
    // 填充價格符號¥
    ctx.setFillStyle("#cb4255");
    ctx.font = "normal normal 15px sans-serif";
    ctx.fillText("¥", that.data.normalPageX - 2, that.data.pricePageY);
    // 填充價格文字
    ctx.font = "normal bold 20px sans-serif";
    ctx.fillText(
      that.data.price,
      that.data.normalPageX + 13,
      that.data.pricePageY
    );
    // 計算價格符號¥ + 價格文字寬度
    let priceWidth = ctx.measureText("¥" + that.data.price).width;
    //有劃線價,才展示
    if (this.data.delPrice) {
      // 填充劃線價文字
      ctx.setFillStyle("#999");
      ctx.font = "normal normal 13px sans-serif";
      ctx.fillText(
        that.data.delPrice,
        that.data.normalPageX + priceWidth,
        that.data.pricePageY
      );
      // 計算劃線價寬度
      let delPriceWidth = ctx.measureText(that.data.delPrice).width;
      // 填充劃線價橫線
      ctx.beginPath();
      ctx.moveTo(
        that.data.normalPageX + priceWidth + 2,
        that.data.pricePageY - 4
      );
      ctx.lineTo(
        that.data.normalPageX + priceWidth + delPriceWidth + 2,
        that.data.pricePageY - 4
      );
      ctx.setStrokeStyle("#999");
      ctx.stroke();
      ctx.closePath();
    }
    // 填充小程序碼
    ctx.drawImage(
      that.data.qrCode,
      that.data.normalPageX + that.data.windowWidth * 0.53,
      that.data.codePageY,
      that.data.codeWidth,
      that.data.codeHeight
    );
    // 填充長按立即購買文本
    ctx.setFillStyle("#333");
    ctx.font = "normal normal 9px sans-serif";
    ctx.fillText(
      "長按分享給好友",
      that.data.normalPageX +
      that.data.windowWidth * 0.53 +
      (that.data.codeWidth - 54) / 2,
      that.data.codePageY + that.data.codeWidth + 10
    );
    ctx.draw(); //繪制到canvas
  },

  // 保存圖片
  savePic: function () {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 50,
      width: that.data.windowWidth * 2,
      height: that.data.contentHeight * 2,
      canvasId: "myCanvas",
      success: function (res) {
        // util.savePicToAlbum(res.tempFilePath);
        wx.hideLoading();
        var tempFilePath = res.tempFilePath;
        that.setData({
          canvasUrl: tempFilePath
        });
        if (tempFilePath !== "") {
          wx.hideLoading();
          wx.previewImage({
            current: that.data.canvasUrl, // 當前顯示圖片的http鏈接
            urls: [that.data.canvasUrl], // 需要預覽的圖片http鏈接列表
            success: function (_res) {
              console.log("預覽成功啦");
            }
          });
        }
      }
    });
  },
  //下載小程序碼
  downloadSkuQrCode: function (url) {
    let that = this;
    wx.downloadFile({
      url: url,
      success: function (res) {
        that.setData({
          qrCode: res.tempFilePath
        });
        wx.hideLoading();
        //生成數(shù)據(jù)
        that.getData();
      },
      fail: function (err) {
        wx.showToast({
          title: "下載商品碼失敗,稍后重試!",
          icon: "none",
          duration: 5000
        });
      }
    });
  },

  //點擊保存到相冊
  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) {
              // utils.aiCardActionRecord(19);
              wx.showModal({
                content: '圖片已保存到相冊,趕緊曬一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  } 
});

3.END

上述代碼小伙伴們可以直接復制到微信開發(fā)者工具里面進行查看功能。以上代碼只是提供思路。具體業(yè)務已經(jīng)樣式需要小伙伴自己去探索啦希望可以幫到有需要的小伙伴溜了溜了

圖文分享.gif

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 發(fā)現(xiàn) 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 15,690評論 4 61
  • 在家無聊,又逢下雨天氣,拾起多日閑置的畫筆,畫畫。今天的成績是:兩張靜物素描。
    黃河故道邊的一個教書匠閱讀 213評論 0 0
  • 5月18日 星期五 天氣 晴 五月的上海,連接著幾日炙熱的燒烤,上班在辦公室里孵空調成了人生的享受,只是鋼筋水...
    Kitty_菁彩人生閱讀 1,789評論 14 12
  • 01 5分鐘起飛法 “just do it”。耐克這句廣告語深入人心,想做就做別拖延,無論成功或失敗,先邁出第一步...
    萌小Q在路上閱讀 282評論 0 4
  • 沈華立 公司:慈溪市創(chuàng)鑫車輛零部件有限公司 六項精進224期利他二組學員 【日精進打卡315天】 【知~學習】 《...
    沈華立閱讀 148評論 0 0

友情鏈接更多精彩內容