小程序 分享 海报生成下载图片

2020-06-11  本文已影响0人  糖醋里脊120625

html部分

<view class="banner">
  <image class="banner-img" mode="aspectFill" src="{{details.cover}}"></image>
</view>
<view class="main">
  <view class="title">
    {{details.title}}
    <!-- <view class="shares-icon" ></view> -->
  </view>
  <view class="con">
    <text>{{details.point}}积分</text>
    <view class="enrolment">剩余名额 {{details.number - details.enroll}}人 </view>
  </view>
  <view class="time">报名期限:{{details.ranage}}</view>
</view>

<view class="content">
  <rich-text nodes='{{details.content}}'></rich-text>
</view>
<view style="width:100%;height:100rpx;"></view>
<view class="footer" style="{{isIphoneX ? 'padding-bottom:66rpx;' : ''}}">
  <!-- <view class="footer-number">{{details.point}}积分</view> -->
  <view class="footer-content" >
    
      <block wx:if='{{details.is_collect == 1}}'>
        <view class="footer-li" bindtap="cancelCollection" data-id='{{details.id}}'>
          <image class="footer-img" mode="aspectFill" src="../../../images/me/show.png" style="width:36rpx;height:36rpx;"></image>
        <view class="footer-text" style="padding-top: 8rpx;font-size: 24rpx;">收藏</view>
         </view>
      </block>
      <block wx:else>
          <view class="footer-li" bindtap="isCollection" data-id='{{details.id}}'>
            <image class="footer-img" mode="aspectFill" src="../../../images/me/shows.png" style="width:36rpx;height:36rpx;"></image>
           <view class="footer-text" style="padding-top: 8rpx;font-size: 24rpx;">收藏</view>
            </view>
      </block>
  
      <view class="footer-li">
        <button open-type='share'  class="share-but">
        <image class="footer-img" src="../../../images/me/weixin.png" style="width:47rpx;height:40rpx;"></image>
        <view class="footer-text">分享链接</view>
         </button>
      </view> 
   
    <view class="footer-li" bindtap="Share">
      <image class="footer-img" src="../../../images/me/penyou.png" style="width:40rpx;height:40rpx;"></image>
      <view class="footer-text">分享海报</view>
    </view>
  </view>
    
  
  <block wx:if='{{details.is_enroll == 0}}'>
      <block wx:if='{{status_title == "进行中"}}'>
        <button class="footer-button" bindtap="SignUp" data-id="{{details.id}}">立即报名</button>
      </block>
      <block wx:else>
        <button class="footer-button" >{{status_title}}</button>
      </block>
  </block>
  <block wx:else>
      <button class="footer-button footer-buttons" >已报名</button>
  </block>
</view>

<frame status='{{status}}' isShow='{{isShow}}' text='{{text}}' bind:_cancel='cancel'></frame>

<!-- 海报 -->
<view class="{{curtain}}" catchtap="Cur">
  <view style="width:100%;">
    <view style='display:flex;justify-content:center;'>
      <view class="curtain-box" >
        <canvas  canvas-id="myCanvas" class="canvas"></canvas>
      </view>
    </view>
    <block wx:if='{{imgshareBut}}'>
      <view style='display:flex;justify-content:center;'>
        <button class="footer-button but" bindtap="saveImageToPhoto" >下载保存</button>
      </view>
    </block>
    
  </view>
</view>

js部分

import HTTP from "../../../utils/request.js";
import utils from "../../../utils/util.js";
var _http = new HTTP();
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    curtain: 'curtains',
    rpx: "",
    rpxheight: "",
    details:{},
    isShow:false,
    status:"",
    text:"",
    ids:"",
    limit_text:"", //仅限那个社区
    imgshare:"", //生成海报链接
    status_title:"加入我们",//是否已结束
    isIphoneX: app.globalData.systemInfo.models ? true : false,
    imgshareBut:false,
    scene:"",
    viewactivity:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      viewactivity: options.activity_id,
    })
  },
  Details(id){
    _http.request({
      url:"/api/activity/detail",
      method:"GET",
      data: { activity_id: this.data.viewactivity}
    }).then(res=>{
      res.data.list.content = res.data.list.content.replace(/\<img/gi, '<img style="max-width:100%;height:auto"')
      this.setData({
        details:res.data.list,
        ids:id
      })
    })
  },
  //报名
  SignUp(e){
    let id = e.currentTarget.dataset.id;
    _http.request({
      url:"/api/activity/checkEnroll",
      method:"POST",
      data: { activity_id : id}
    }).then(res=>{
      if (res.data.code == 7005) {
        this.setData({
          isShow: true,
          status: "Enough"
        })
      } else if(res.data.code == 7004){
        this.setData({
          isShow:true,
          status:"NoOneself"
        })
      } else if (res.data.code == 7003){
        this.setData({
          isShow: true,
          status: "Personal",
          text:"才能参加活动呦"
        })
      }else if(res.data.code == 7002){
        utils.showToast('不需要重复报名','none')
      } else if (res.code == 200){
        let obj={}
        obj.cover = this.data.details.cover 
        obj.num = this.data.details.number - this.data.details.enroll
        wx.navigateTo({
          url: '/pages/activity/enterFor/enterFor?scene=' + id + '&point=' + this.data.details.point + '&data='+JSON.stringify(obj),
        })
      }
    })
  },
  //删除弹框
  cancel(){
    this.setData({
      isShow:false
    })
  },
  // 取消收藏
  cancelCollection(e){
    let id = e.currentTarget.dataset.id
    _http.request({
      url:"/api/activity/unCollectDo",
      method:"get",
      data:{ activity_id: id }
    }).then(res=>{
      if (res.code == 200) {
        this.setData({
          [`details.is_collect`]: 0
        })
        wx.showToast({
          title: '取消收藏成功',
          icon: "none"
        })
      } else {
        // wx.showToast({
        //   title: is_collect,
        //   icon: "none"
        // })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.getSystemInfo({
      success: res => {
        let rpx = res.windowWidth / 375;
        let rpxheight = res.windowHeight / 603
        this.setData({
          rpx: rpx,
          rpxheight: rpxheight
        })
      },
    })
    this.Details(this.data.viewactivity)
  },
  //收藏
  isCollection(e) {
    let id = e.currentTarget.dataset.id;
    _http.request({
      url: "/api/activity/collectDo",
      method: "POST",
      data: { activity_id: id }
    }).then(e => {
      if(e.code == 200){
        this.setData({
          [`details.is_collect`] : 1
        })
        wx.showToast({
          title: '收藏成功',
          icon: "none"
        })
      }else{
        // wx.showToast({
        //   title: is_collect,
        //   icon: "none"
        // })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.setStorageSync("returns", true)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  Share() {
    this.setData({
      curtain: "curtain"
    })
    this.generate()
  },
  //退出海报
  Cur(){
    /* 该隐藏的隐藏 */
    this.setData({
      curtain: "curtains",
      imgshareBut:false
    })
  },
  //生成海报
  generate() {
   
    this.gener().then(res=>{
      this.setData({ imgshare: res })
    })
  },
  gener(){

    //二维码
    return new Promise((reslove, sej) => {
      wx.showLoading({
        title: '正在加载中...',
        icon: 'none'
      })
      let that = this;
      let qrcode = new Promise((reslove, sej) => {
        _http.request({
          url: "/api/qrcode",
          method: "GET",
          data: {
            id: that.data.ids
          }
        }).then(res => {
          console.log(res)
          wx.getImageInfo({
            src: res.data.path,
            success(res) {
              reslove(res.path)
            },
            fail(err) {
              
              console.log(err);
            },
          });
        })
      });
      //背景
      let avatar = new Promise((reslove, sej) => {
        console.log(that.data.details.cover)
        wx.getImageInfo({
          src: that.data.details.cover,
          success(res) {
            reslove(res.path)
          },
          fail(err) {
            console.log(err);
          },
        });
      });
      Promise.all([qrcode, avatar]).then((res) => {
        const ctx = wx.createCanvasContext('myCanvas');
        let rpx = that.data.rpx, heightrpx = that.data.rpxheight;
        ctx.fillStyle = "#FFFFFF";
        ctx.fillRect(0, 0, 345 * rpx, 520 * heightrpx);
        ctx.drawImage(res[1], 0, 0, 345 * rpx, 200);
        ctx.setFontSize(18 * rpx);
        ctx.setFillStyle("#333");
        var text = that.data.details.title//这是要绘制的文本
        var chr = text.split("");//这个方法是将一个字符串分割成字符串数组
        var temp = "";
        var row = [];
        for (var a = 0; a < chr.length; a++) {
          if (ctx.measureText(temp).width < 250) {
            temp += chr[a];
          }
          else {
            a--; //这里添加了a-- 是为了防止字符丢失,效果图中有对比
            row.push(temp);
            temp = "";
          }
        }
        row.push(temp);
        //如果数组长度大于2 则截取前两个
        if (row.length > 2) {
          var rowCut = row.slice(0, 2);
          var rowPart = rowCut[1];
          var test = "";
          var empty = [];
          for (var a = 0; a < rowPart.length; a++) {
            if (ctx.measureText(test).width < 220) {
              test += rowPart[a];
            }
            else {
              break;
            }
          }
          empty.push(test);
          var group = empty[0] + "..."//这里只显示两行,超出的用...表示
          rowCut.splice(1, 1, group);
          row = rowCut;
        }
        for (var b = 0; b < row.length; b++) {
          ctx.fillText(row[b], 30 * rpx, 230 + b * 20 * rpx);
        }
        ctx.drawImage(res[0], ((345 * rpx) - 110) / 2, 320+b*10, 110 * rpx, 110);
        ctx.fillText("长按识别或扫码查看活动详情", ((345 * rpx) - 230) / 2, 440 + b * 20 * rpx);
        ctx.setFontSize(14 * rpx);
        ctx.setFillStyle("#999");
        ctx.fillText("剩余名额:" + that.data.details.enroll + "人", 220 * rpx, 240 + b * 20 * rpx);
        ctx.setFontSize(18 * rpx);
        ctx.setFillStyle("#d11515");
        ctx.fillText(that.data.details.point + "积分", 30 * rpx, 240 + b * 20 * rpx);
        ctx.setFontSize(14 * rpx);
        // if (that.data.limit_text) {
        //   ctx.fillText(that.data.limit_text, 30 * rpx, 290 + b * 20 * rpx);
        // }
        ctx.setFillStyle("#666666");
        ctx.fillText("报名期限:" + that.data.details.ranage, 30 * rpx, 270 + b * 20 * rpx);
        ctx.fillText("此产品海报由【吴门共益】小程序生成", ((345 * rpx) - 220) / 2, 465 + b * 20 * rpx);
        that.setData({ imgshareBut :true })
        wx.hideLoading();
        ctx.draw(true, setTimeout(function () {     //为什么要延迟100毫秒?大家测试一下
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 646 * rpx,
            height: 966 * rpx,
            destWidth: 646 * rpx,
            destHeight: 966 * rpx,
            canvasId: 'myCanvas',
            success: res => {
              wx.hideLoading();
              reslove(res.tempFilePath)
            }
          }, that)
        }, 1000))
      })
    })
  },
  //下载海报
  saveImageToPhoto(){
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imgshare,
      success(res) {
        console.log(res)
        wx.showModal({
          content: '图片已保存到相册,赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              /* 该隐藏的隐藏 */
              that.setData({
                curtain: "curtains"
              })
            }
          }, fail: function (res) {
            console.log(11111)
          }
        })
      },
      fail: res => {
        console.log(res)
      }
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    console.log("xxx")
  }
})
上一篇 下一篇

猜你喜欢

热点阅读