最完美最全的小程序生成分享朋友圈海报图

a 夏天 提交于 2020-01-07 02:51:49

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

以上是两张分享朋友圈海报效果图,接下来开始教大家如何用代码制作:

页面:

<!--分享海报第一步弹框-->
<view wx:if="{{showShare}}">
    <view class="gray-view" bindtap="noshare">
        <view class=""></view>
    </view>
    <view class="share-view">
        <view>
            <view class="goods">
                <span class="line"></span>
                <view class="goods-text">分享到</view>
                <span class="line"></span>
            </view>
            <view class="share-type" bindtap="wxShare">
                <view>
                    <button style="text-align:center" open-type='share'>
                        <image src="/images/other/weixin.png"/>
                        <view>微信</view>
                    </button>
                </view>
                <view style="text-align:center" bindtap="poster">
                    <image src="/images/other/haibao.png"/>
                    <view>生成海报</view>
                </view>
            </view>
            <view class="divLine"></view>
            <view class="cancel" bindtap="noshare">取消</view>
        </view>
    </view>
</view>
<!--分享海报第二步弹框-->
<view class="canvas-v"  wx:if="{{show}}">
    <view style="width:80%">
        <view>
            <canvas canvas-id='canone' style='position: fixed;top:{{showTop}}px;width:{{canvasWidth}}px; height:{{canvasWidth+50}}px;background-color:#fff;' disable-scroll='true'>

            </canvas>
        </view>
        <view class="btn-view" style="top:{{canvasWidth+100}}px;">
            <view class="button-v">
                <view>
                    <button class="weui-btn mini-btn" type="default" bindtap="cencal" style="width:{{canvasWidth/2}}px;">取消</button>
                </view>
                <view>
                    <button class="weui-btn mini-btn" type="primary" bindtap="save" style="width:{{canvasWidth/2}}px;">保存分享</button>
                </view>
            </view>
        </view>
    </view>
</view>
<!--授权弹窗-->
<view class="modal-box" wx:if='{{openSet}}'>
    <view class="modal-content">
        <view class="content-title">提示信息</view>
        <view class="content-text">
            请授权【保存到相册】权限
        </view>
    </view>
    <view class="modal-btns">
        <view class="weui-flex">
            <view class="weui-flex__item">
                <button class="dialog-btn cancel" open-type="exit" bindtap="disAgreeGrantPhoto">拒绝授权</button>
                <button class="dialog-btn confirm" open-type="openSetting" bindtap="openSetting">确认授权</button>
            </view>
        </view>
    </view>
</view>

样式:

/*分享海报*/
.gray-view{
  position: fixed;
  top: 0;
  background-color: #b3b2b0;
  filter:alpha(Opacity=80);
  -moz-opacity:0.5;opacity: 0.5;
  height: 1200rpx;
  width: 100%;
}
.share-view{
  position: fixed;
  bottom: 0;
  background-color:#fff;
  height: 300rpx;
  width: 100%;
}
.share-type{
  display: flex;
  justify-content: space-around;
}
.share-type image{
  width: 100rpx;
  height: 100rpx;
}
.share-type button{
  width: 150rpx;
  height: 150rpx;
  line-height: 45rpx;
  background: transparent;
  font-size: 30rpx;
}
.share-type button::after{
  border: none;
}
.cancel{
  text-align: center;
  font-size: 34rpx;
  line-height: 65rpx;
}
.goods{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60rpx;
  margin-top: 10rpx;
}

.goods-text,.image-text{
  font-weight: bold;
  font-size:36rpx;
  padding: 0 50rpx 0 50rpx
}
.line {
  display: inline-block;
  width: 120rpx;
  border-top: 1px solid #C0C0C0 ;
}
.divLine{
  background: #E0E3DA;
  width: 100%;
  height: 5rpx;
}


.canvas-v{
  display: flex;
  justify-content: center;
}

.btn-view{
  position: fixed;
}
.button-v{
  display: flex;
  justify-content: space-around;
}

/*弹框样式*/
.modal-box {
  position: fixed;
  background: rgba(0, 0, 0, 0.4);
  top: 0rpx;
  width: 100%;
  height: 100%;
}
.modal-content {
  background: #fff;
  width: 600rpx;
  margin: 42% auto 0;
  justify-content: center;
  align-items: center;
  border-bottom: 1px solid #ebebec;
}
.content-title {
  height: 100rpx;
  text-align: center;
  font-size: 1.2rem;
  padding-top: 10rpx;
}
.content-text {
  padding:50px 0;
  text-align: center;
}
.modal-btns {
  width: 600rpx;
  margin: 0 auto;
  justify-content: center;
  align-items: center;
}
.dialog-btn {
  border-radius: 0;
  background: #fff;
  height: 100rpx;
  width: 100%;
}
.dialog-btn::after {
  border: none;
  border-radius: 0;
}
.cancel {
  color: #ccc;
}
.confirm {
  border-left: 1px solid #ebebec;
  color: #60d048;
}

js:

data:{
  commodityImg:[],//分享海报
  showShare:false,
  show:false,
  canvasWidth:'',
  canvasHeight:'',
  showTop:-500,//需要消失的时候就设置为-500,显示的时候就50
  smallcodepic:'',
  openSet:false
},
onLoad: function (options) {
  //海报
  var myCanvasWidth;
  var myCanvasHeight;
  wx.getSystemInfo({
    success: function (res) {
      myCanvasWidth = res.windowWidth *80/100
      myCanvasHeight = res.windowHeight - 200
    },
  })
  that.setData({
    canvasWidth: myCanvasWidth,
    canvasHeight: myCanvasHeight
  })
  //初始化分享时的底表图片
  that.initSmallCode(that);
},
//海报
noshare(){
  this.setData({
    showShare: false
  })
},
showshare:function(){
  this.setData({
    showShare: true
  })
},
//绘制海报(核心)
poster:function(){
  let that = this;
  let img='';
  this.noshare();
  this.setData({
    show:true,
    showTop:50
  });
  var url = app.globalData.serverip+'/sysWheel/s_getShareOne';//获取海报顶部图片
  var data = {};
  app.globalData.httpUtils.ajaxRequestJson(url,data,'POST',function(data){
    if(data.data.code==0){
      img = app.globalData.serverip+"/"+data.data.object;
      wx.getImageInfo({
        src: img,
        success:function(res){
          var ctx = wx.createCanvasContext('canone', that);
          //1、绘制顶部图片
          ctx.setTextAlign('center')
          ctx.setFillStyle('#fff')
          ctx.fillRect(0, 0, that.data.canvasWidth, that.data.canvasWidth+72)
          ctx.drawImage(res.path, 10, 10, that.data.canvasWidth-20, that.data.canvasWidth-160)
          //2、绘制主体文字
          ctx.setTextAlign('left')
          ctx.setFillStyle('#000000')
          ctx.setFontSize(12)
          var str = that.data.article.shortcontent;
          str = str.replace(new RegExp('&nbsp;','g'),"");
          if(str.length>175){
            str = str.substr(0,175)+"...";
          }else{
            str = str;
          }
          //标题换行 16是自已定的,为字体的高度
          const nameWidth = ctx.measureText(str).width;
          that.wordsWrap(ctx, str, nameWidth, that.data.canvasWidth-30, 10, 17 + that.data.canvasWidth - 170 + 20, 16);
          //3、绘制标题
          ctx.setFontSize(13)
          ctx.setFillStyle('#000000')
          ctx.setTextAlign('right')
          ctx.setShadow(10, 50, 50, 'gray')
          if(that.data.article.title.length>13){
            ctx.fillText("---《"+that.data.article.title.substr(0,13)+"..."+"》", that.data.canvasWidth-10,that.data.canvasWidth+5)
          }else{
            ctx.fillText("---《"+that.data.article.title+"》", that.data.canvasWidth-5,that.data.canvasWidth+5)
          }

          //4、绘制小程序码
          ctx.setTextAlign('left')
          ctx.setFillStyle('gray')
          ctx.drawImage(that.data.smallcodepic, 20, 17 + that.data.canvasWidth - 70 + 45, 50, 50)
          ctx.setFontSize(12)
          ctx.setTextAlign('right')
          ctx.fillText('(小智读书▪长按二维码阅读)', that.data.canvasWidth-10, 17 + that.data.canvasWidth - 65 + 85)

          ctx.draw(false, () => {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              canvasId: 'canone',//shareCanvas 为制定 绘图canvas 的ID
              success: (res) => {
              },
              complete: (res) => {
                wx.hideLoading()
              }
            })
          });
        }
      })
    }
  });
},
//绘图保存到本地-1
save:function(){
  let that = this;
  // 相册授权
  wx.getSetting({
    success(res) {
      // 进行授权检测,未授权则进行弹层授权
      if (!res.authSetting['scope.writePhotosAlbum']) {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success () {
            that.saveImage(filePath)
          },
          // 拒绝授权时,则进入手机设置页面,可进行授权设置
          fail() {
            wx.openSetting({
              success: function (data) {
                console.log("openSetting success");
              },
              fail: function (data) {
                  that.setData({
                      show:false
                  })
                  console.log("openSetting fail");
                  that.setData({
                      openSet:true
                  })
              }
            });
          }
        })
      } else {
        // 已授权则直接进行保存图片
        that.saveImage()
      }
    },
    fail(res) {
      console.log(res);
    }
  })
},
//绘图保存到本地-2
saveImage:function(){
    let that = this
    wx.canvasToTempFilePath({
        canvasId: 'canone',
        quality:'jpg',
        success(res) {
            wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function success(res) {
                    console.log('saved::' + res.savedFilePath);
                    wx.showToast({
                        title: '保存成功',
                    })
                    that.cencal()
                },
                complete: function fail(e) {
                    console.log(e.errMsg);
                }
            });
        },
        complete: function complete(e) {
            console.log(e.errMsg);
        }
    })
},
//文字换行处理
wordsWrap(ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight){
  let lineWidth = 0;
  let lastSubStrIndex = 0;
  for (let i = 0; i < name.length; i++) {
    lineWidth += ctx.measureText(name[i]).width;
    if (lineWidth > maxWidth) {
      ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY);
      srartY += wordsHight;
      lineWidth = 0;
      lastSubStrIndex = i;
    }
    if (i == name.length - 1) {
      ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY);
    }
  }
},
//隐藏
cencal:function(){
  this.setData({
    show:false,
    showTop:-500
  })
},
//同意授权隐藏弹框,同时重新加载海报
openSetting:function(){
    this.setData({
        openSet:false
    })
    this.poster();
},
//不同意授权
disAgreeGrantPhoto:function(){
    wx.showModal({
        title: '提示',
        content: '未授权将无法保存图片到手机相册'
    })
    this.setData({
        openSet:false
    })
},
//初始化小程序码
initSmallCode: function (that) {
  var url = app.globalData.serverip+'/customerWeixinLogin/getWxaqrcodeUrl';
  var data = {"scene":that.data.id,"page":"pages/index/index"};
  app.globalData.httpUtils.ajaxRequestJson(url,data,'POST',function(data){
    if(data.data.code==0){
      var smallcodepic = app.globalData.serverip+"/"+data.data.object;
      wx.getImageInfo({
        src: smallcodepic,
        success:function(res){
          that.setData({
            smallcodepic:res.path
          })
        }
      })
    }
  });
}

前提是有一个按钮绑定poster方法

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!