微信小程序> 头像加相框微信小程序

头像加相框微信小程序

浏览量:10162 时间: 来源:applebadm

微信小程序—头像加相框
今天我们要实现一个给头像加相框功能的小程序。
大约分三个步骤
1.在有相框列表的页面上传图片
2.进行裁剪或者旋转功能
这里用到的头像裁剪插件是https://github.com/wx-plugin/image-cropper
3.生成头像保存到本地

上代码!

//选择用户自己头像图片  upload() {    wx.chooseImage({      count: 1, // 默认9      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有      success(res) {        const src = res.tempFilePaths[0]        //将选择的图传至cropper页处理        wx.navigateTo({          url: `../cropper/cropper?src=${src}`        })      }    })  }

上传图片拿到图片的路径传到cropper页面去,cropper就是裁剪页面。在这个文件进行裁剪和旋转等方法的编写。
先把image-cropper文件放到与cropper同目录中,然后在cropper中引入。
cropper文件
cropper.json文件中添加image-cropper

{  "navigationBarTitleText": "裁剪图片",    "navigationBarBackgroundColor": "#000",  "usingComponents": {    "image-cropper": "../image-cropper/image-cropper"  }}

cropper.wxml

<image-cropper id="image-cropper" limit_move="{{true}}" disable_rotate="{{true}}" width="{{width}}" height="{{height}}" imgSrc="{{src}}" bindload="cropperload" bindimageload="loadimage" bindtapcut="clickcut"></image-cropper>    <view class='bottom'>        <view bindtap='cancel'>取消</view>        <view catchtouchstart='rotate' catchtouchend='end' data-type="rotate">旋转</view>        <view catchtap='confirm'>确定</view>    </view>

cropper.wxss

page{  background:rgb(14, 13, 13);}.bottom{  position: absolute;  width:100%;  bottom:50rpx;  display: flex;  z-index: 10;  justify-content: space-around;  color:#fff;}

cropper.js

Page({  data: {    src:'',    width: 300,//宽度    height: 300,//高度  },  onLoad: function (options) {    this.cropper = this.selectComponent("#image-cropper");    this.setData({      src: options.src    });  },  cropperload(e) {    console.log('cropper加载完成');  },  loadimage(e){    wx.hideLoading();    this.cropper.imgReset();  },  clickcut(e) {    //图片预览    wx.previewImage({      current: e.detail.url, // 当前显示图片的http链接      urls: [e.detail.url] // 需要预览的图片http链接列表    })  },   rotate() {    //在用户旋转的基础上旋转90°    this.cropper.setAngle(this.cropper.data.angle += 90);  },  end(e) {    clearInterval(this.data[e.currentTarget.dataset.type]);  },  confirm(e){    this.cropper.getImg(function(e){      console.log(e)      let avatar = e.url;        //获取到裁剪后的图片传到保存页面去        wx.redirectTo({          url: `../savePic/savePic?avatar=${avatar}`        })    })  },  //取消返回上一页面  cancel(){    wx.navigateBack({      url:'../makePic/makePic'    })  }  })

savePic–保存图片文件
savePic.wxml

<view wx:if="{{layerShow}}" class="maskLayer">            <view class="layerBox">                <view class="layerBoxP">                    <text>长按头像保存</text>                </view>            </view>        </view>    <view class="savebg">      <view class="content">        <view class="head_border">          <view>           <canvas canvas-id="myCanvas" class='bger'>       <image class="frame_width" bindlongtap="generate" src="{{bgsrc}}"></image>        <image src="{{src}}" class="avatar"></image></canvas>              <view style='position:absolute;left:400rpx;'><canvas  canvas-id='ahaucanvas' style='height:840px;width:840px;position:absolute;left:400rpx;'>            </canvas>            </view>           </view>        </view>       </view>  <view class="desc" bindtap='goMakePic'>重新生成</view>

savePic.js

const app = getApp();   Page({  data: {    src: '',    bgsrc: '',    bgcss: '',    layerShow:true,    timer: '',//定时器名字    countDownNum: '60'//倒计时初始值  },  goMakePic(){    wx.navigateTo({      url: '/pages/makePic/makePic',    })  },  countdown(){    let that=this;    let countDownNum = that.data.countDownNum;    that.setData({    timer:setInterval(function(){      countDownNum--;      that.setData({        countDownNum: countDownNum,        layerShow:false      })      if(countDownNum==0){        clearInterval(that.data.timer)      }    },2000)    })  },  onLoad(option) {    var that = this;    var bgcss = app.globalData.toubgsrc.substr(14, 2);    //此处的app.globalData.toubgsrc是一个全局变量 在相框列表拿到被选中的相框    that.setData({      bgsrc: app.globalData.toubgsrc,      bgcss: bgcss    });      let { avatar } = option;    if (avatar) {      that.setData({        src: avatar      });    }  },  onReady(){    this.countdown();  },  //生成头像  generate() {    var self = this;    var contex = wx.createCanvasContext('ahaucanvas');     var avatarurl_width = 840; //画布宽    var avatarurl_heigth = 840; //画布高    contex.drawImage(self.data.src, 127, 127,600,600);    contex.restore();    contex.save();    contex.beginPath(); //开始绘制    contex.drawImage(self.data.bgsrc, 0, 0, avatarurl_width, avatarurl_heigth);     contex.restore();    contex.draw(true, setTimeout(function () {      wx.canvasToTempFilePath({ //导出图片        width: 840,        height: 840,        destWidth: 840,        destHeight: 840,        canvasId: 'ahaucanvas',        success: res => {          wx.saveImageToPhotosAlbum({            filePath: res.tempFilePath,            success: function (data) {              console.log(data);              wx.showToast({                title: '保存成功',                icon: 'success',                duration: 2000              })            },            fail: function (err) {              if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {                // console.log("用户拒绝,再次发起授权")                wx.openSetting({                  success(settingdata) {                    console.log(settingdata)                    if (settingdata.authSetting['scope.writePhotosAlbum']) {                      // console.log('获取权限成功,给出再次点击图片保存到相册的提示。')                      wx.showToast({                        title: '请再次保存',                        icon: 'success',                        duration: 2000                      })                    }                   }                })              }            }          })        }      }, this)    }, 100))  },  goMakePic(){    wx.navigateTo({      url: '/pages/makePic/makePic',    })  }})

一个头像加相框的小程序就差不多做好了。不是很完美,还请大家多多指教O(∩_∩)O

小程序

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

最新资讯

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎