头像加相框微信小程序

微信小程序—头像加相框
今天我们要实现一个给头像加相框功能的小程序。
大约分三个步骤
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

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值