我是靠谱客的博主 俊秀柜子,这篇文章主要介绍小程序canvas换行与canvas生成图片分享朋友圈及分享好友,现在分享给大家,希望可以做个参考。

小程序canvas多余文字"..."处理    文字换行显示   分享给好友及朋友圈  保存图片到本地

所有的图片均要是https的  先用 wx.downloadFile处理到本地  适配可用wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function(rect) {console.log(rect)}).exec()

wxll


<!-- 分享遮罩 -->
<view class="shade" hidden='{{!isShare}}' catchtouchmove='true' catchtap="closeShare" data-target="selfShare">
  <view class='list-shade' wx:if="{{isCanvas}}">
    <image src='../../images/shadeLogo.png' style='width:226rpx;height:62rpx;float:left;display:block;'></image>
    <view class='shade-img'>
      <image src="{{primary_pic_url}}" mode='widthFix' style='width:300rpx;height:331.2rpx;'></image>
    </view>
    <view class='list-bottom'>
      <view class='bottom-left'>
        <view class="content-title" style='font-size:24rpx;'>{{goods.name}}</view>
        <view style="font-size:22rpx;font-family:PingFangSC-Semibold;font-weight:600;color:rgba(0,0,0,1);margin-top:40rpx;">
          拼单价:
          <text style="font-size:28rpx;font-family:PingFang-SC-Heavy;font-weight:800;color:rgba(232,135,38,1);" wx:if="{{isleaguer==1}}">¥{{goods.market_price}}</text>
          <text style="font-size:28rpx;font-family:PingFang-SC-Heavy;font-weight:800;color:rgba(232,135,38,1);" wx:else>¥{{kolmarketPrice}}</text>
        </view>
        <block  wx:if="{{goods.generalize_rebates!=null}}">
        <view class="content-cash" wx:if="{{isMember==1}}">返利¥{{goods.generalize_rebates}}</view>
        </block>
      </view>
      <view class='bottom-right'>
        <image src="{{memberUrl}}" wx:if="{{memberUrl}}" style='width:142rpx;height:142rpx;display:block;' mode="aspectFill"></image>
        <image src='{{kolQrUrl}}' style='width:142rpx;height:142rpx;display:block;' mode="aspectFill" wx:else></image>
        <text style="font-size:20rpx;font-family:PingFang-SC-Heavy;font-weight:500;color:rgba(0,0,0,1);">长按识别二维码</text>
      </view>
    </view>
  </view>
  <view class='poste_box' id='canvas-container' wx:else>
    <!--canvas不能用display:block和none 设置样式opacity为0真机无效 因此设置top位置在屏幕外面即可-->
    <canvas canvas-id="myCanvas" style="width:100%;height:750rpx;"></canvas>
  </view>
  <view class="shade-bottom">
    <button open-type="share" class='bottom-one' catchtap="shareMask">
      <image src='../../images/wx1.png' style='width:56rpx;height:56rpx;'></image>
      <text>分享给好友</text>
    </button>
    <button class='bottom-one' catchtap='all'>
      <image src='../../images/wx2.png' mode="aspectFill" style='width:56rpx;height:56rpx;'></image>
      <text>分享朋友圈</text>
    </button>
  </view>
</view>

<!-- 分享图已经保存到手机 -->
<view class='openVideo' wx:if="{{isShareData}}" data-target="self">
  <view class='shareFriend'>
    <view class='close' catchtap='closeShareTap'>X</view>
    <view class='shade-txt'>
      <image src='../../images/collagetip1.png' class='tip-img'></image>
      <view>分享图已经保存到手机</view>
      <view>分享保存的图片到朋友圈即可</view>
    </view>
  </view>
</view>

css

.shade view {

overflow: none !important;

}



/* 遮罩 */



.shade {

width: 100%;

height: 100%;

position: fixed;

z-index: 9999;

top: 0;

left: 0;

overflow-y: hidden;

background-color: rgba(0, 0, 0, 0.5) !important;

background-color: #000;

filter: Alpha(opacity=50);

}



.shade-content {

width: 100%;

height: auto;

background: rgba(255, 255, 255, 1);

position: absolute;

bottom: 0;

}



.shade-member {

width: 91%;

height: 266rpx;

background: rgba(255, 255, 255, 1);

border-radius: 16rpx;

margin: 31vh auto 0 auto;

text-align: left;

overflow: hidden;

}



.shade-list {

width: 91%;

display: flex;

margin: 0 auto;

align-content: center;

justify-content: flex-start;

/* overflow: none!important; */

}



/* list-shade */



.list-shade {

width: 580rpx;

height: auto;

background: rgba(255, 255, 255, 1);

/* border-radius: 20rpx; */

margin: 100rpx auto 0;

overflow: hidden;

padding: 44rpx 44rpx;

box-sizing: border-box;

}



.close {

color: rgba(232, 135, 38, 1);

float: right;

font-size: 40rpx;

box-sizing: border-box;

font-weight: 900;

}



.shade-img {

width: 300rpx;

height: 300rpx;

margin: 80rpx auto 0;

text-align: center;

}



.list-bottom {

display: flex;

justify-content: space-between;

align-content: center;

}



.bottom-left {

/* margin-top: 90rpx; */

}



.shade-bottom {

position: absolute;

bottom: 0rpx;

width: 100%;

height: 152rpx;

background: rgba(255, 255, 255, 1);

border-radius: 20rpx 20rpx 0px 0px;

display: flex;

justify-content: space-around;

align-items: center;

}



.bottom-one {

margin: 0;

padding: 0;

list-style-type: none;

line-height: 0;

background-color: #fff;

border: 0;

border-color: #fff;

width: 200rpx;

height: 100rpx;

}



.bottom-one image {

display: block;

margin: 0 auto 20rpx auto;

}



/*canvas宽高*/



.poste_box {

width: 77%;

margin: auto;

margin-top: 100rpx;

background-color: #fff;

}



canvas {

display: block;

margin: 0;

padding: 0;

}



.shareFriend {

width: 580rpx;

height: 540rpx;

background: rgba(255, 255, 255, 1);

border-radius: 20rpx;

margin: 256rpx auto 0;

}



.close {

padding-top: 30rpx;

margin-right: 30rpx;

color: rgba(232, 135, 38, 1);

text-align: right;

font-size: 40rpx;

box-sizing: border-box;

font-weight: 900;

}



.shade-txt {

text-align: center;

padding: 32rpx 0 0;

box-sizing: border-box;

}



.shade-txt view {

font-size: 40rpx;

font-family: PingFangSC-Semibold;

font-weight: 600;

color: rgba(41, 41, 41, 1);

}



.tip-img {

width: 104rpx;

height: 86rpx;

margin: 120rpx 0 20rpx 60rpx;

}

js


data{
    isShare: false, //分享遮罩
    isCanvas: true, //是否显示canvas 分享朋友圈
    type: '', //全部生成图片类型
    isShareMask: 0, //分享给朋友
}
 
 // 获取会员二维码
  getCode(e) {
    // wx.showLoading({
    //   title: '加载中...',
    //   mask: true
    // })
    let that = this
    let goods_id = that.data.id; //获取产品id
    let memberUserId = wx.getStorageSync('userId')
    console.log(memberUserId)
    util.request(api.****, {
      goodsId: goods_id,
      memberUserId: memberUserId
    }).then(function(res) {
      if (res.errno === 0) {
        var memberUrl = res.data.memberUrl
        that.setData({
          memberUrl: memberUrl
        })
      }
    });
  },


 // 分享
  onShareAppMessage: function(res) {
    console.log(res)
    let that = this;
    let goods_id = that.data.goods.id; //获取产品id
    let goods_title = that.data.goods.name; //获取产品标题
    let kolPinkId = that.data.kolPinkId;
    var imgUserPath = that.data.primary_pic_url;
    var gallery = this.data.gallery;
    let memberUserId = wx.getStorageSync('userId')
    console.log(memberUserId)
    let isMember = that.data.isMember; //是否是会员
    let leaguer = that.data.leaguer
    console.log(gallery)
    var imgUserPath = []
    for (var i = 0; i < gallery.length; i++) {
      imgUserPath = gallery[i].img_url;
    }
    console.log(imgUserPath)
    let kolProductId = that.data.kolProductId
    if (kolPinkId) {
      return {
        title: goods_title,
        path: '/pages/goods/goods?id=' + goods_id + '&title=' + goods_title + '&kolPinkId=' + kolPinkId + '&kolProductId=' + kolProductId + '&memberUserId=' + memberUserId,
        imageUrl: imgUserPath
      }
    } else {
      return {
        title: goods_title,
        path: '/pages/goods/goods?id=' + goods_id + '&title=' + goods_title + '&memberUserId=' + memberUserId,
        imageUrl: imgUserPath
      }
    }
  },


 /**
   * canvas获取商品图片
   */
  getGoodsImg() {
    let that = this
    // wx.showLoading({
    //   title: '加载中...',
    //   mask: true
    // });
    var imgUserPath = that.data.primary_pic_url;
    wx.downloadFile({
      url: imgUserPath, //路径
      success: function(res) {
        // console.log(res)
        wx.hideLoading();
        if (res.statusCode === 200) {
          var codeSrc = res.tempFilePath;
          console.log(codeSrc)
          that.getQRImg(codeSrc); //继续下载二维码图片
        } else {
          wx.showToast({
            title: '下载失败!',
            icon: 'none',
            duration: 2000,
            success: function() {}
          })
        }
      }
    })
  },
  /**
   * canvas获取二维码图片
   */
  getQRImg(codeSrc) {
    let that = this
    // wx.showLoading({
    //   title: '加载中...',
    //   mask: true
    // });
    if (that.data.isleaguer == 1) {
      console.log(that.data.memberUrl)
      wx.downloadFile({
        url: that.data.memberUrl, //路径
        success: function(res) {
          if (res.statusCode === 200) {
            var qrCode = res.tempFilePath;
            that.showImg(codeSrc, qrCode);
          } else {
            wx.showToast({
              title: '下载失败!',
              icon: 'none',
              duration: 2000,
              success: function() {}
            })
          }
        }
      })
    }
    console.log(that.data.kolQrUrl)
    if (that.data.kolId == 0) {
      wx.downloadFile({
        url: that.data.kolQrUrl, //路径
        success: function(res) {
          console.log(res)
          if (res.statusCode === 200) {
            var qrCode = res.tempFilePath;
            that.showImg(codeSrc, qrCode);
          } else {
            wx.showToast({
              title: '下载失败!',
              icon: 'none',
              duration: 2000,
              success: function() {}
            })
          }
        }
      })
    }
  },
  //绘制图片 
  showImg: function(codeSrc, qrCode) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
      let kolmarketPrice = that.data.kolmarketPrice
      console.log(kolmarketPrice)
      const ctx = wx.createCanvasContext('myCanvas');
      var imgPath = '../../images/shadeLogo.png';
      var cashPath = '../../images/cashbg.png';
      var width = "";
      wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function(rect) {
        console.log(rect)
        var height = rect.height;
        var right = rect.right;
        var width = rect.width * 0.8;
        var left = rect.left;
        ctx.setFillStyle('#fff');
        ctx.fillRect(0, 0, rect.width, height);
        //绘制图像到画布 x y width height logo
        ctx.drawImage(imgPath, left / 2, rect.top - 37, rect.top * 2 + 13, rect.top - 19);
        //绘制图像到画布  商品图片
        ctx.drawImage(codeSrc, rect.width / 2 - 75, rect.top + 10, width / 2 + 45, width / 2 + 45)
        ctx.stroke()
        //创建文字
        //文案 x y商品标题
        //获取产品标题
        let goodsname = that.data.goodsname; //获取产品标题
        let generalize_rebates = that.data.goods.generalize_rebates;
        // let goodsname = "很骄傲福建省规划,扩散到科技;馆黑胡椒猴哥【猴哥寡】妇进口国艰苦奋斗"
        var chr = goodsname.split(""); //这个方法是将一个字符串分割成字符串数组
        console.log(chr)
        var temp = "";
        var row = [];
        ctx.setFontSize(16)
        ctx.setFillStyle("#000")
        //文字换行处理开始
        for (var a = 0; a < chr.length; a++) {
          if (ctx.measureText(temp).width < 180) {
            console.log(ctx.measureText(temp).width)
            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 < 150) {
              console.log(ctx.measureText(test).width)
              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], left / 2, width + b * 22, rect.top * 3 + 25);
        }
        //文字换行处理结束
        // 商品价格
        ctx.setFontSize(14)
        ctx.setFillStyle('#000000')
        ctx.fillText('拼单价', left / 2, width + 80)
        // ctx.stroke()
        // 商品价格
        ctx.setFontSize(14)
        ctx.setFillStyle('#E88726')
        ctx.fillText('¥' + kolmarketPrice, left / 2, width + 100)
        // 绘制返利
        if (that.data.isMember == 1) {
          wx.getImageInfo({
            src: cashPath,
            success: function(res) {
              console.log(res)
              //绘制图片
              ctx.drawImage(cashPath, left * 1.8, width + 80, res.width / 2, res.height / 2);
              ctx.setFontSize(12)
              ctx.setFillStyle('#fff')
              ctx.fillText('返利' + generalize_rebates, left * 2.1, width + 100)
            }
          })

        }
        //二维码文字 
        ctx.setFontSize(12)
        ctx.setFillStyle('#000000')
        ctx.fillText('长按识别二维码', rect.top * 4 - 8, width + 90)
        // ctx.stroke()
        //绘制图像到画布 二维码
        ctx.drawImage(qrCode, rect.top * 4, width, rect.top + 20, rect.top + 20)
        ctx.stroke()
      }).exec()

      //渲染
      setTimeout(function() {
        ctx.draw();
        wx.hideLoading();
      }, 100)
      if (that.data.type == 'all') {
        this.saveShareImg()
      }
    

      //渲染
      setTimeout(function () {
        ctx.draw();
        wx.hideLoading();
      }, 100)
      if (that.data.type == 'all') {
        this.saveShareImg()
      }
    }
  },
  /**
   * 生成图片
   */
  saveShareImg() {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
      duration: 3000
    })
    setTimeout(function() {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        quality: 1,
        fileType: 'jpg', //图片的质量,目前仅对 jpg 有效。取值范围为 (0, 1],不在范围内时当作 1.0 处理。
        success: function(res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              that.setData({
                isShareData: 1,
                isShare: 0
              })
            },
            fail: function(res) {
              wx.showToast({
                title: 'res.errMsg',
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  /**
   * 生成保存图片
   */
  all: function() {
    var that = this
    that.setData({
      type: 'all',
      isCanvas: false
    })
    this.getGoodsImg();
  },
})

获取微信头像  谨记(要配置微信的下载安全域名)(https://wx.qlogo.cn)
/**
   * 先下载头像图片
   */
  getAvaterInfo: function() {
    // wx.showLoading({
    //   title: '头像生成中...',
    //   mask: true
    // });
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    wx.downloadFile({
      url: userInfo.avatarUrl, //头像图片路径
      success: function(res) {
        console.log(res)
        wx.hideLoading();
        if (res.statusCode === 200) {
          var avaterSrc = res.tempFilePath; //下载成功返回结果
          that.getQrCode(avaterSrc);
        } else {
          wx.showToast({
            title: '头像下载失败!',
            icon: 'none',
            duration: 2000,
            success: function() {
            }
          })
        }
      }
    })
  },
wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function(rect) {
//绘制圆形头像
if (avaterSrc){
        wx.getImageInfo({
          src: avaterSrc,
          success: function(res) {
            console.log(res)
            ctx.setStrokeStyle('#fff');
            ctx.save();
            ctx.beginPath() //开始创建一个路径
            //画一个圆形裁剪区域
            ctx.arc(res.width / 1.57, res.width / 2, res.width / 10 - 0.2, 0, 2 * Math.PI, false)
            ctx.clip() //裁剪
            //绘制图片
            ctx.drawImage(res.path, res.width / 2 + 5, res.width / 2 - 13, res.width / 5 - 0.4, res.height / 5 - 0.4)
            ctx.restore() //恢复之前保存的绘图上下文
            ctx.setFontSize(12)
            ctx.setFillStyle('#fff')
            //绘制昵称
            var uName = that.data.nickName
            if (uName == 0 || uName == undefined) {
              return false;
              //大于四个字,多余的'...'替换
            } else if (uName.length > 4) {
              var str = uName.substr(0, uName.length - 2);
              ctx.fillText(str + "..." + '邀请你注册遇尚', res.width - 28, res.width / 2 + 4)
            } else {
              ctx.fillText(uName + '邀请你注册遇尚', res.width - 28, res.width / 2 + 4)
            }
            ctx.setFillStyle('#fff')
          }
        })
      }
    }).exec()

 

最后

以上就是俊秀柜子最近收集整理的关于小程序canvas换行与canvas生成图片分享朋友圈及分享好友的全部内容,更多相关小程序canvas换行与canvas生成图片分享朋友圈及分享好友内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部