微信小程序canvas分享海报功能

微信小程序canvas分享海报,包含拒绝授权后重新打开授权设置。

这篇文章完善了第一次拒绝授权后再次点击可以打开授权设置,希望可以帮助到爱学习的道友

这里是效果图,图片可以百度上找。

微信小程序canvas分享海报功能

话不多说,直接上代码

最重要的一点,千万不要忘记在json文件里面注册组件和wxml里面引用组件

wxml

<button class='btn' catchtap='createPoster' >生成海报</button>
<my-poster id="getPoster" types="{{type}}" isflag="{{isflag}}" title="{{goods_title}}" bigImg="{{share.img}}" qrcode="{{share.rcode}}" >
</my-poster> 

js

data:{ isflag: false // 海报模态框 }
// 生成海报
 createPoster:function(){
 this.setData({
 isflag: true
 })
 this.selectComponent('#getPoster').getAvaterInfo();
 },

组件wxml

<view hidden="{{!isflag}}" catchtouchmove="return" class="con-poster" bindtap='closePoster'>
 <!-- 模态框 -->
 <view class='modialog'>
 <view class='canvas-box' id='canvas-container'>
 <canvas canvas-id="myCanvas" style="width:100%;height:100%;"/>
 </view>
 </view>
 <!-- 保存图片按钮 -->
 <view class='save-img' catchtap='saveBtn'>保存图片</view>
</view>

组件wxss

.con-poster{
 width: 100%;
 height: 100%;
 background: rgba(0,0.5);
 position: fixed;
 top: 0;
 left: 0;
 z-index: 999;
 }
 .modialog{
 width: 660rpx;
 height: 750rpx;
 margin: 100rpx auto 0;
 }
 .canvas-box{
 width: 660rpx;
 height: 750rpx;
 background: #fff;
 }
.save-img{
 width: 660rpx;
 height: 100rpx;
 margin: 30rpx auto 0;
 font-size: 32rpx;
 display: flex;
 justify-content: center;
 align-items: center;
 color: #fff;
 background:linear-gradient(90deg,rgba(56,219,248,1),rgba(81,171,255,1));
}

组件js

properties: {
 isflag:{ // 控制组件开关
 type: Boolean,value: true
 }
 bigImg:{ // 大图
 type: String,value: ''
 },qrcode:{ // 二维码
 type: String,title:{ // 标题
 type: String,value: '大幅度开发'
 }
}

data: {
 imgHeight: 0
},methods: {
 //关闭海报
 closePoster: function () {
 this.setData({
 isflag: false
 })
 },// 提示框
 toast: function(msg,callback){
 wx.showToast({
 title: msg,icon: 'none',success(){
  callback && (setTimeout(function(){
  callback()
  },1500))
 }
 })
 },//下载产品大图
 getAvaterInfo: function () {
 wx.showLoading({
 title: '生成中...',mask: true
 });
 var that = this;
 that.setData({
 isflag: true
 })
 var productImage = that.data.bigImg;
 if (productImage) {
 wx.downloadFile({
  url: productImage,success: function (res) {
  wx.hideLoading();
  if (res.statusCode === 200) {
  var productSrc = res.tempFilePath;
  that.calculateImg(productSrc,function (data) {
  that.getQrCode(productSrc,data);
  })
  } else {
  that.toast('产品图片下载失败!',() =>{
  var productSrc = "";
  that.getQrCode(productSrc);
  })
  }
  },fail: function (err) {
  wx.hideLoading();
  that.toast('请求失败,网络错误',() => {
  that.closePoster()
  })
  }
 })
 } else {
 wx.hideLoading();
 var productSrc = "";
 that.getQrCode(productSrc);
 }
 },//下载二维码
 getQrCode: function (productSrc,imgInfo = "") {
 wx.showLoading({
 title: '生成中...',mask: true,});
 var that = this;
 var productCode = that.data.qrcode;
 if (productCode) {
 wx.downloadFile({
  url: productCode,success: function (res) {
  wx.hideLoading();
  if (res.statusCode === 200) {
  var codeSrc = res.tempFilePath;
  that.sharePosteCanvas(productSrc,codeSrc,imgInfo);
  } else {
  that.toast('二维码下载失败!',() => {
  var codeSrc = "";
  that.sharePosteCanvas(productSrc,imgInfo);
  })
  }
  },fail: function () {
  wx.hideLoading();
  that.toast('请求失败,网络错误',() => {
  that.closePoster()
  })
  }
 })
 } else {
 wx.hideLoading();
 var codeSrc = "";
 that.sharePosteCanvas(productSrc,codeSrc);
 }
 },//canvas绘制分享海报
 sharePosteCanvas: function (avaterSrc,imgInfo){
 wx.showLoading({
 title: '生成中...',})
 var that = this;
 const ctx = wx.createCanvasContext('myCanvas',that);
 var width = "";
 const query = wx.createSelectorQuery().in(this);
 query.select('#canvas-container').boundingClientRect(function (rect) {
 var width = rect.width;
 var height = rect.height;
 var left = rect.left;
 ctx.setFillStyle('#fff');
 ctx.fillRect(0,width,height);

 //海报大图
 if (avaterSrc) {
  if (imgInfo) {
  var imgheght = parseFloat(imgInfo);
  }
  ctx.drawImage(avaterSrc,imgheght ? imgheght : width);
  ctx.setFontSize(14);
  ctx.setFillStyle('#fff');
  ctx.setTextAlign('left');
 }

 //海报标题
 if (that.data.title) {
  const CONTENT_ROW_LENGTH = 22; // 正文 单行显示字符长度
  let [contentLeng,contentArray,contentRows] = that.textByteLength((that.data.title).substr(0,40),CONTENT_ROW_LENGTH);
  ctx.setTextAlign('left');
  ctx.setFillStyle('#000');
  ctx.setFontSize(15);
  let contentHh = 22 * 1;
  for (let m = 0; m < contentArray.length; m++) {
  ctx.fillText(contentArray[m],15,imgheght + 35 + contentHh * m);
  }
 }

 // 绘制二维码
 if (codeSrc) {
  ctx.drawImage(codeSrc,left + 215,imgheght + 20,width / 4,width / 4)
  ctx.setFontSize(10);
  ctx.setFillStyle('#000');
 }
 }).exec()
 setTimeout(function () {
 ctx.draw();
 wx.hideLoading();
 },1000)
 },// 封装每行显示的文本字数
 textByteLength(text,num) { // text为传入的文本 num为单行显示的字节长度
 let strLength = 0;
 let rows = 1;
 let str = 0;
 let arr = [];
 for (let j = 0; j < text.length; j++) {
 if (text.charCodeAt(j) > 255) {
  strLength += 2;
  if (strLength > rows * num) {
  strLength++;
  arr.push(text.slice(str,j));
  str = j;

  rows++;
  }
 } else {
  strLength++;
  if (strLength > rows * num) {
  arr.push(text.slice(str,j));
  str = j;
  rows++;
  }
 }
 }
 arr.push(text.slice(str,text.length));
 return [strLength,arr,rows] // [处理文字的总字节长度,每行显示内容的数组,行数]
 },//计算图片尺寸
 calculateImg: function (src,cb) {
 var that = this;
 wx.getSystemInfo({
 success(res2) {
  var imgHeight = (res2.windowWidth * 0.65) + 130;
  that.setData({
  imgHeight: imgHeight
  })
  cb(imgHeight - 130);
 }
 })
 },// 点击保存按钮
 saveBtn(){
 var _this = this
 wx.getSetting({
 success(res) {
  if (res.authSetting['scope.writePhotosAlbum']) { // 第一次授权,并且成功
  _this.saveShareImg();
  } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) { // 未授权
  wx.authorize({
  scope: 'scope.writePhotosAlbum',success() {
  _this.saveShareImg();
  },fail() {
  _this.toast('您没有授权,无法保存到相册')
  }
  })
  } else { // 第一次授权失败,现在打开设置
  wx.showModal({
  title: '警告',content: '请打开授权,否则无法将图片保存在相册中!',success(result) {
  if (result.confirm) {
   wx.openSetting({
   success(settingResult) {
   if (settingResult.authSetting['scope.writePhotosAlbum']) {
   _this.saveShareImg();
   } else {
   _this.toast('您没有授权,无法保存到相册')
   }
   }
   })
  }
  }
  })
  }
 }
 })
 },// 保存到相册
 saveShareImg: function () {
 var that = this;
 wx.showLoading({
 title: '正在保存',})
 setTimeout(function () {
 wx.canvasToTempFilePath({
  canvasId: 'myCanvas',success: function (res) {
  var tempFilePath = res.tempFilePath;
  wx.saveImageToPhotosAlbum({
  filePath: tempFilePath,success() { // 保存
  wx.hideLoading()
  that.toast('图片保存成功',() =>{
   that.closePoster();
  })
  },fail: function (err) { // 取消保存
  wx.hideLoading()
  that.toast('保存失败')
  }
  })
  }
 },that);
 },1000);
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


kindeditor4.x代码高亮功能默认使用的是prettify插件,prettify是Google提供的一款源代码语法高亮着色器,它提供一种简单的形式来着色HTML页面上的程序代码,实现方式如下: 首先在编辑器里面插入javascript代码: 确定后会在编辑器插入这样的代码: <pre
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代码高亮,因为SyntaxHighlighter的应用非常广泛,所以将kindeditor默认的prettify替换为SyntaxHighlighter代码高亮插件 上一篇“让kindeditor显示高亮代码”中已经
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高
JS对象如何转为json格式字符串
JS怎么获取图片原始宽高
怎么在click事件中调用多个js函数
js如何往数组中添加新元素
js如何拆分字符串
JS怎么对数组内元素进行求和
JS如何判断屏幕大小
js怎么解析json数据
js如何实时获取浏览器窗口大小
原生JS实现别踩白块小游戏(五)
原生JS实现别踩白块小游戏(一)