微信小程序生成分享圖片,保存到本地

1.頁面canvas

<canvas canvas-id="shareCanvas" style="width:600px;height:900px"></canvas>

2.繪製圖片小程序

經過使用wx.downloadFile或wx.getImageInfo這個API來下載一個網絡圖片到本地(並可獲取該圖片的尺寸等其餘信息),而後調用ctx.drawImage方法將圖片繪製到畫布上,填滿畫布api

wx.downloadFile({
     url: 'https://nlwxapp.oss-cn-beijing.aliyuncs.com/static/butiful.png',
     success (res) {
         if (res.statusCode === 200) {
             that.bgImgPath = res.tempFilePath// 背景圖
         }
     }
})

3.小程序碼網絡

經過後臺接口得到小程序碼,將小程序碼下載到本地app

4.繪製this

circleImg(ctx, img, x, y, r){
                ctx.save();
                var d = 2 * r;
                var cx = x + r;
                var cy = y + r;
                ctx.beginPath();
                ctx.arc(cx, cy, r, 0, 2 * Math.PI);
                // ctx.setStrokeStyle('rgba(0,0,0,0)')
                canvas.stroke()
                ctx.clip();
                ctx.drawImage(img, x, y, d, d);
                ctx.restore()
              },
            showImg() {
                var that = this;
                const ctx = wx.createCanvasContext('myCanvas');
                
                // 設置背景
                ctx.setFillStyle('#E72454')
                ctx.fillRect(0,0,315,393)
                
                // 繪製圖片
                ctx.drawImage(that.bgImgPath, 0, 0, 315, 250)
                // 繪製頭像
                that.circleImg(ctx,that.headIcon,315/2-50, 20, 50)
                
                
                //建立文字
                ctx.setFontSize(18)
                ctx.setFillStyle('#fff')
                ctx.setTextAlign('center')
                ctx.fillText(that.userInfo.nickName + '邀請你一塊兒分獎金', 315 / 2, 140)
                ctx.stroke()
                
                ctx.setFontSize(42)
                ctx.setFillStyle('#FFD288')
                ctx.textAlign = 'center'
                ctx.fillText(that.message.money, 157, 180)
                
                var a = ctx.measureText(that.message.money).width
                ctx.setFontSize(16)
                ctx.setFillStyle('#FFD288')
                ctx.fillText('元', 157 + 5 + a/2, 180)
                ctx.stroke()
                
                // 繪製小程序碼
                ctx.drawImage(that.wxCode, 315/2-75, 200, 150, 150)
                
                context.setFontSize(12)
                context.setFillStyle("#fff")
                context.setTextAlign("center")
                context.fillText("長按識別小程序", 157, 310)
                ctx.stroke()
                //渲染
                ctx.draw()
            
                
            },

5.將canvas滬指的內容轉成圖片url

//須要把canvas轉成圖片後才能保存
wx.canvasToTempFilePath({ // 生成圖片並把繪製的圖片路徑保存到一個變量
       x: 0,
       y: 0,
       width: 315,
       height: 393,
       destWidth: 1260,  //2倍關係
       destHeight: 1572, //2倍關係
       canvasId: 'myCanvas',
       success: function (res) {
       //關鍵 賦值給變量
           that.shareImgSrc = res.tempFilePath
           that.saveImg2()
       },
       fail: function (res) {
            console.log(res)
       }
})

6.將圖片保存到本地spa

var that = this
wx.saveImageToPhotosAlbum({ // 這張圖片保存到本地相冊
     //shareImgSrc爲canvas賦值的圖片路徑
      filePath: that.shareImgSrc,
      success(res) {
            console.log('保存成功');
            wx.showModal({
                 title: '保存成功',
                 content: '圖片成功保存到相冊了,快去發朋友圈吧~',
                 showCancel: false,
                 confirmText: '確認',
                 confirmColor: '#21e6c1',
                 success: function (res) {
                       if (res.confirm) {
                           console.log('用戶點擊肯定');
                       }
                 }
              })
       }
   })

完整代碼rest

 

<template>
    <div>
        <canvas canvas-id="myCanvas" :class="{'topScroll':isOpacity}"></canvas>
     </div>
</template>

<script>
    export default {
        components: {
        },
        props: {
        },
        data() {
            return {
                isOpacity: true,
                deviceWidth: 0,
                deviceHeight: 0,
                shareImgSrc: '',
                bgImgPath: '',
                headIcon:'',
                wxCode: ''
            }
        },
        onShow: function () {
        },
        onLoad: function (){
            var that = this;
            wx.getSystemInfo({
              success(res) {
                that.deviceWidth = res.windowWidth,
                that.deviceHeight = res.windowHeight
              }
            })
            let data = { path: '/pages/activity/groupActivityOne' }
            this.api.getWXCode(data,(res)=>{
                // 將圖片臨時保存到本地 
                wx.downloadFile({
                  url: res.data.data.url,
                  success (res) {
                    if (res.statusCode === 200) {
                        that.wxCode = res.tempFilePath // 小程序碼圖片
                        wx.downloadFile({
                          url: wx.getStorageSync('userInfo').avatarUrl,
                          success (res) {
                            if (res.statusCode === 200) {
                                that.headIcon = res.tempFilePath // 頭像
                                wx.downloadFile({
                                    url: 'https://nlwxapp.oss-cn-beijing.aliyuncs.com/static/butiful.png',
                                    success (res) {
                                    if (res.statusCode === 200) {
                                            that.bgImgPath = res.tempFilePath// 背景圖
                                        }
                                    }
                                })
                            }
                          }
                        })
                    }
                  }
                })
            })
        },
        created(){
            if (wx.getStorageSync('userInfo')) {
              this.userInfo = wx.getStorageSync('userInfo')
            }
        },
        methods: {
            circleImg(ctx, img, x, y, r){
                ctx.save();
                var d = 2 * r;
                var cx = x + r;
                var cy = y + r;
                ctx.beginPath();
                ctx.arc(cx, cy, r, 0, 2 * Math.PI);
                // ctx.setStrokeStyle('rgba(0,0,0,0)')
                canvas.stroke()
                ctx.clip();
                ctx.drawImage(img, x, y, d, d);
                ctx.restore()
              },
            showImg() {
                var that = this;
                const ctx = wx.createCanvasContext('myCanvas');
                
                // 設置背景
                ctx.setFillStyle('#E72454')
                ctx.fillRect(0,0,315,393)
                
                // 繪製圖片
                ctx.drawImage(that.bgImgPath, 0, 0, 315, 250)
                // 繪製頭像
                that.circleImg(ctx,that.headIcon,315/2-50, 20, 50)
                
                
                //建立文字
                ctx.setFontSize(18)
                ctx.setFillStyle('#fff')
                ctx.setTextAlign('center')
                ctx.fillText(that.userInfo.nickName + '邀請你一塊兒分獎金', 315 / 2, 140)
                ctx.stroke()
                
                ctx.setFontSize(42)
                ctx.setFillStyle('#FFD288')
                ctx.textAlign = 'center'
                ctx.fillText(that.message.money, 157, 180)
                
                var a = ctx.measureText(that.message.money).width
                ctx.setFontSize(16)
                ctx.setFillStyle('#FFD288')
                ctx.fillText('元', 157 + 5 + a/2, 180)
                ctx.stroke()
                
                // 繪製小程序碼
                ctx.drawImage(that.wxCode, 315/2-75, 200, 150, 150)
                
                context.setFontSize(12)
                context.setFillStyle("#fff")
                context.setTextAlign("center")
                context.fillText("長按識別小程序", 157, 310)
                ctx.stroke()
                //渲染
                ctx.draw()
            
                //須要把canvas轉成圖片後才能保存
                wx.canvasToTempFilePath({ // 生成圖片並把繪製的圖片路徑保存到一個變量
                  x: 0,
                  y: 0,
                  width: 315,
                  height: 393,
                  destWidth: 1260,  //2倍關係
                  destHeight: 1572, //2倍關係
                  canvasId: 'myCanvas',
                  success: function (res) {
                    //關鍵 賦值給變量
                    that.shareImgSrc = res.tempFilePath
                    that.saveImg2()
                  },
                  fail: function (res) {
                    console.log(res)
                  }
                })
            },
            saveImg2() {
                var that = this
                wx.saveImageToPhotosAlbum({ // 這張圖片保存到本地相冊
                    //shareImgSrc爲canvas賦值的圖片路徑
                    filePath: that.shareImgSrc,
                    success(res) {
                        console.log('保存成功');
                        wx.showModal({
                            title: '保存成功',
                            content: '圖片成功保存到相冊了,快去發朋友圈吧~',
                            showCancel: false,
                            confirmText: '確認',
                            confirmColor: '#21e6c1',
                            success: function (res) {
                                if (res.confirm) {
                                    console.log('用戶點擊肯定');
                                }
                            }
                        })
                    }
                })
            }
        }
    }
</script>

<style>
 canvas{
      width: 315px;
      height: 393px;
      position: fixed;
      left: 75rpx;
      top: 50%;
      margin-top: -435rpx;
    }

   /*控制canvas顯示和隱藏 top值要大 要保證能溢出到屏幕外面*/
   .topScroll{
       position: absolute;
       top: -2000rpx;
    }code

</style>
相關文章
相關標籤/搜索