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

时间:2024-02-20 19:17:01

1.页面

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

2.绘制图片

通过使用wx.downloadFile或wx.getImageInfo这个API来下载一个网络图片到本地(并可获取该图片的尺寸等其他信息),然后调用ctx.drawImage方法将图片绘制到画布上,填满画布

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

3.小程序码

通过后台接口获得小程序码,将小程序码下载到本地

4.绘制

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沪指的内容转成图片

//需要把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.将图片保存到本地

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(\'用户点击确定\');
                       }
                 }
              })
       }
   })

完整代码

 

<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;
    }

</style>