美文网首页
小程序前端canvas将页面生成图片海报并保存

小程序前端canvas将页面生成图片海报并保存

作者: Piemon_Jay | 来源:发表于2019-10-12 14:14 被阅读0次

    需求是在产品详情页面有个按钮,点击生成一张图片,图片上有产品信息、产品图、小程序码等元素。
    先来看下最终的效果:


    image.png

    网上教程很多,基本都是canvas实现,这里也不例外,所以对canvas不熟悉的朋友建议先去补一下canvas基础。
    参考的那篇blog找不到了,只知道是个妹子写的,简单易懂,还很贴心的给了代码(虽然勉强拿过来用,但还是踩了些坑,改了很多东西)
    话不多说,下面上代码:
    首先,在详情页面添加一大一小2个canvas以及一个生成canvas的按钮,为什么要2个canvas下面会讲到:

    <!--product.wxml-->
    <image class="shareImg" src="xxx.png" mode="widthFix" bindtap="showshare"></image>
    <view class="sharebox" hidden="{{hideshare}}">
      <view class='canvas_box'>
        <canvas style="margin:0 auto;width:280px; height:380px;position:relative;z-index:10;top:30px;" canvas-id="myCanvas" hidden="{{canvasHidden}}"></canvas>
        <canvas style="margin:0 auto;width:560px; height:760px;position:fixed;top:-999999px;left:0;" canvas-id="myCanvasBig"></canvas>
        <view class='canvas_btn' bindtap='savetup'>
          <image src='../../images/btn_bg.png'></image>
          保存图片
        </view>
      </view>
      <view class="bound"></view>
    </view>
    

    canvas初始状态hideshare为true,通过按钮的showshare事件控制

      showshare:function(){
        var that = this;
        that.setData({
          hideshare:false
        },()=>{that.downLoad()})
      },
    

    触发showshare函数后,会回调download函数,作用是把需要绘制的网络图片保存至本地(因为canvas只能绘制本地图片,绘制网络图片画布上是空白,网上还有其他解决方法,试了下都没用,只有这个成功了)

      downLoad: function (e) {
        var that = this;
        wx.showLoading({
          title: '正在绘制图片',
        })
        //缓存canvas背景图
        wx.downloadFile({
          url: that.data.bgImgPath,//网络路径
          success: function (res3) {
            //背景图
            that.setData({
              bgImgPath: res3.tempFilePath
            })
            console.log(res3.tempFilePath)
            console.log('开始绘制图片')
            that.drawimg();//绘图的函数
            // 结束加载中提示
            wx.hideLoading()
          }
        })
      },
    

    that.drawimg函数就是绘制canvas的主要函数了,细节一点的话可以放到setData回调里,下面来看下最主要的drawimg函数:

      drawimg: function () {
        var that = this;
        //1. 请求后端API生成小程序码
        //that.getQr();
    
        //2. canvas绘制文字和图片
        const ctx = wx.createCanvasContext('myCanvas');
        var avatarUrl = that.data.avatarUrl;//头像
        var nickName = that.data.nickName;//昵称
        var bgImgPath = that.data.bgImgPath;//封面大图
        var proname = that.data.proname;
        console.log(bgImgPath)
        var xcxcode = that.data.xcxcode;//二维码
    
        //填充背景(图片的白色背景)
        ctx.setFillStyle('#ffffff');
        ctx.fillRect(0, 0, 280, 380);//坐标和宽高
    
    
        //绘制品牌
        ctx.setFontSize(18);
        ctx.setFillStyle('#000000');
        ctx.fillText(nickName, 35, 315);
    
        //绘制名称
        ctx.setFontSize(14);
        ctx.setFillStyle('#000000');
        ctx.fillText("产品:"+proname, 35, 350);
    
        // 第三张图片(封面大图)
        ctx.drawImage(bgImgPath, 0, 0, 280, 280);
    
        //绘制一条虚线
    
        // ctx.strokeStyle = 'blue';
        // ctx.beginPath();
        // ctx.setLineWidth(1);
        // ctx.setLineDash([2, 4]);
        // ctx.moveTo(0, 270);
        // ctx.lineTo(280, 270);
        // ctx.stroke();
    
        //绘制二维码
        ctx.drawImage(xcxcode, 170, 285, 80, 80);
    
        ctx.draw();
      },
    

    到这里其实已经能达到图上效果,但是保存图片时出现了意外,保存至本地的图片比较模糊,所以再补上一个2倍的canvas,同样放进drawimg函数(这里我把这个大canvas通过定位隐藏到了视图外)

    const ctx2 = wx.createCanvasContext('myCanvasBig');
    
        //填充背景(图片的白色背景)
        ctx2.setFillStyle('#ffffff');
        ctx2.fillRect(0, 0, 560, 760);//坐标和宽高
    
        //绘制昵称
        ctx2.setFontSize(36);
        ctx2.setFillStyle('#000000');
        ctx2.fillText(nickName, 70, 630);
    
        //绘制标题
        ctx2.setFontSize(28);
        ctx2.setFillStyle('#000000');
        ctx2.fillText("产品:" + proname, 70, 700);
    
        // 第三张图片(封面大图)
        ctx2.drawImage(bgImgPath, 0, 0, 560, 560);
    
        //绘制一条虚线
    
        // ctx2.strokeStyle = 'blue';
        // ctx2.beginPath();
        // ctx2.setLineWidth(1);
        // ctx2.setLineDash([2, 4]);
        // ctx2.moveTo(0, 540);
        // ctx2.lineTo(560, 540);
        // ctx2.stroke();
    
        //绘制二维码
        ctx2.drawImage(xcxcode, 340, 570, 160, 160);
    
        ctx2.draw();
    
    

    接下来就是保存了,直接调用wx的方法

    savetup: function () {
        var that = this;
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 560,
          height: 760,
          destWidth: 560,
          destHeight: 760,
          canvasId: 'myCanvasBig',
          success: function (res) {
            //调取小程序当中获取图片
            console.log(res.tempFilePath);
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success(res) {
                wx.showModal({
                  title: '图片保存成功!',
                  content: '请将图片分享到朋友圈',
                  showCancel: false,
                  confirmText: '知道了',
                  confirmColor: '#72B9C3',
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定');
                      that.setData({
                        hideshare:true
                      })
                    }
                  }
                })
              }
            })
          },
          fail: function (res) {
            console.log(res)
          }
        })
      },
    

    到这里就over了。
    需要注意的就两个点,一个是绘制网络图片时先保存获取本地路径,还有一个就是绘制图片时在两个canvas上绘制,一倍的用于页面显示,2倍的用于保存。
    wxss比较简单,偷个懒就不放出来了。

    相关文章

      网友评论

          本文标题:小程序前端canvas将页面生成图片海报并保存

          本文链接:https://www.haomeiwen.com/subject/icpiyctx.html