微信小程序--头像框项目新增功能及页面设计

这两周主要进行头像框的项目的新增功能,以及相关界面的设计和实现

上传微信头像

按钮设置微信小程序默认的获取用户信息的按钮类型,点击自动调用相关函数获取信息

  <button class="btn_upload" open-type='getUserInfo' bindgetuserinfo="upload">

调用自带函数获取用户信息,为了之后在页面间传递图片参数,将获取到的用户微信头像转换为临时本地路径

 upload:function(e){
    this.setData({
      src:e.detail.userInfo.avatarUrl
    })

    wx.getImageInfo({
      src:this.data.src,
      success: res => {
        this.data.src=res.path
      }
    })
  },
本地上传

调用为微信自带的函数进行本地相册或者摄像机的使用,若获取到图片那么跳转到裁剪头像界面

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

携带获取到的图片参数跳转到upload页面
upload.xwml

<!--upload.wxml-->
<!--用户选择自己的框内头像页-->
<import src="../../cropper/cropper.wxml" />
<view class="cropper-wrapper">
  <template is="cropper" data="{{...cropperOpt}}" />
  <view class="cropper-buttons">
    <view class="upload" bindtap="uploadTap">
      重新选择
    </view>
    <view class="getCropperImage" bindtap="getCropperImage">
      确定
    </view>
  </view>
</view>

upload.css

.cropper-wrapper{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    justify-content: center;
    height: 100%;
    background-color: #000000;
}

.cropper-buttons{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    justify-content: center;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 50px;
    line-height: 50px;
    background-color: rgba(0, 0, 0, 0.95);
    color: #04b00f;
}

.cropper-buttons .upload, .cropper-buttons .getCropperImage{
    width: 50%;
    text-align: center;
}
.cropper{
    position: absolute;
    top: 0;
    left: 0;
}

upload.js

// pages/upload/upload.js
//cropper是个轮子,代码因分享而有活力
import weCropper from '../../cropper/cropper.js'

const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = device.windowHeight - 50

Page({
  data: {
    cropperOpt: {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 300) / 2,
        width: 300,
        height: 300
      }
    }
  },
  touchStart(e) {
    this.wecropper.touchStart(e)
  },
  touchMove(e) {
    this.wecropper.touchMove(e)
  },
  touchEnd(e) {
    this.wecropper.touchEnd(e)
  },

  //把裁剪后的图传回madeph的onLoad
  getCropperImage() {
    this.wecropper.getCropperImage((avatar) => {
      if (avatar) {
        //  获取到裁剪后的图片
        wx.redirectTo({
          url: `../index/index?avatar=${avatar}`
        })
      } else {
        console.log('获取图片失败,请稍后重试')
      }
    })
  },

  //用户点了重新选择图片
  uploadTap() {
    const self = this
    //再选一次
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success(res) {
        let src = res.tempFilePaths[0]
        //  获取裁剪图片资源后,给data添加src属性及其值
        self.wecropper.pushOrign(src)
      }
    })
  },

  //得到madeph传过来的图像
  onLoad(option) {
    // do something
    const { cropperOpt } = this.data
    const { src } = option;
    // console.log(this.data);
    if (src) {
      Object.assign(cropperOpt, { src })
      new weCropper(cropperOpt)
        .on('ready', function (ctx) {
          // console.log(`wecropper is ready for work!`)
        })
        .on('beforeImageLoad', (ctx) => {
          console.log(`before picture loaded, i can do something`)
          console.log(`current canvas context:`, ctx)
          wx.showToast({
            title: '上传中',
            icon: 'loading',
            duration: 20000
          })
        })
        .on('imageLoad', (ctx) => {
          // console.log(`picture loaded`)
          // console.log(`current canvas context:`, ctx)
          wx.hideToast()
        })
    }
  }
})

cropper.wxml

<template name="cropper">
    <canvas
            class="cropper"
            disable-scroll="true"
            bindtouchstart="touchStart"
            bindtouchmove="touchMove"
            bindtouchend="touchEnd"
            style="width:{{width}}px;height:{{height}}px;background-color: rgba(0, 0, 0, 0.8)"
            canvas-id="{{id}}">
    </canvas>
</template>

cropper.js

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
      (global.weCropper = factory());
}(this, (function () {
  'use strict';

  var version = "1.1.4";

  /**
   * Created by sail on 2017/6/11.
   */
  var device = void 0;
  var TOUCH_STATE = ['touchstarted', 'touchmoved', 'touchended'];

  function firstLetterUpper(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  function setTouchState(instance) {
    for (var _len = arguments.length, arg = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      arg[_key - 1] = arguments[_key];
    }

    TOUCH_STATE.forEach(function (key, i) {
      if (arg[i] !== undefined) {
        instance[key] = arg[i];
      }
    });
  }

  function validator(instance, o) {
    Object.defineProperties(instance, o);
  }

  function getDevice() {
    if (!device) {
      device = wx.getSystemInfoSync();
    }
    return device;
  }

  var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
    return typeof obj;
  } : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  };
  var classCallCheck = function (instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  };

  var createClass = function () {
    function defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
      }
    }

    return function (Constructor, protoProps, staticProps) {
      if (protoProps) defineProperties(Constructor.prototype, protoProps);
      if (staticProps) defineProperties(Constructor, staticProps);
      return Constructor;
    };
  }();
  var slicedToArray = function () {
    function sliceIterator(arr, i) {
      var _arr = [];
      var _n = true;
      var _d = false;
      var _e = undefined;

      try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);

          if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;
        _e = err;
      } finally {
        try {
          if (!_n && _i["return"]) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }

      return _arr;
    }

    return function (arr, i) {
      if (Array.isArray(arr)) {
        return arr;
      } else if (Symbol.iterator in Object(arr)) {
        return sliceIterator(arr, i);
      } else {
        throw new TypeError("Invalid attempt to destructure non-iterable instance");
      }
    };
  }();

  var tmp = {};

  var DEFAULT = {
    id: {
      default: 'cropper',
      get: function get$$1() {
        return tmp.id;
      },
      set: function set$$1(value) {
        if (typeof value !== 'string') {
          console.error('id\uFF1A' + value + ' is invalid');
        }
        tmp.id = value;
      }
    },
    width: {
      default: 750,
      get: function get$$1() {
        return tmp.width;
      },
      set: function set$$1(value) {
        if (typeof value !== 'number') {
          console.error('width\uFF1A' + value + ' is invalid');
        }
        tmp.width = value;
      }
    },
    height: {
      default: 750,
      get: function get$$1() {
        return tmp.height;
      },
      set: function set$$1(value) {
        if (typeof value !== 'number') {
          console.error('height\uFF1A' + value + ' is invalid');
        }
        tmp.height = value;
      }
    },
    scale: {
      default: 2.5,
      get: function get$$1() {
        return tmp.scale;
      },
      set: function set$$1(value) {
        if (typeof value !== 'number') {
          console.error('scale\uFF1A' + value + ' is invalid');
        }
        tmp.scale = value;
      }
    },
    zoom: {
      default: 5,
      get: function get$$1() {
        return tmp.zoom;
      },
      set: function set$$1(value) {
        if (typeof value !== 'number') {
          console.error('zoom\uFF1A' + value + ' is invalid');
        } else if (value < 0 || value > 10) {
          console.error('zoom should be ranged in 0 ~ 10');
        }
        tmp.zoom = value;
      }
    },
    src: {
      default: 'cropper',
      get: function get$$1() {
        return tmp.src;
      },
      set: function set$$1(value) {
        if (typeof value !== 'string') {
          console.error('id\uFF1A' + value + ' is invalid');
        }
        tmp.src = value;
      }
    },
    cut: {
      default: {},
      get: function get$$1() {
        return tmp.cut;
      },
      set: function set$$1(value) {
        if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') {
          console.error('id\uFF1A' + value + ' is invalid');
        }
        tmp.cut = value;
      }
    },
    onReady: {
      default: null,
      get: function get$$1() {
        return tmp.ready;
      },
      set: function set$$1(value) {
        tmp.ready = value;
      }
    },
    onBeforeImageLoad: {
      default: null,
      get: function get$$1() {
        return tmp.beforeImageLoad;
      },
      set: function set$$1(value) {
        tmp.beforeImageLoad = value;
      }
    },
    onImageLoad: {
      default: null,
      get: function get$$1() {
        return tmp.imageLoad;
      },
      set: function set$$1(value) {
        tmp.imageLoad = value;
      }
    },
    onBeforeDraw: {
      default: null,
      get: function get$$1() {
        return tmp.beforeDraw;
      },
      set: function set$$1(value) {
        tmp.beforeDraw = value;
      }
    }
  };

  /**
   * Created by sail on 2017/6/11.
   */
  function prepare() {
    var self = this;

    var _getDevice = getDevice(),
      windowWidth = _getDevice.windowWidth;

    self.attachPage = function () {
      var pages = getCurrentPages();
      //  获取到当前page上下文
      var pageContext = pages[pages.length - 1];
      //  把this依附在Page上下文的wecropper属性上,便于在page钩子函数中访问
      pageContext.wecropper = self;
    };

    self.createCtx = function () {
      var id = self.id;

      if (id) {
        self.ctx = wx.createCanvasContext(id);
      } else {
        console.error('constructor: create canvas context failed, \'id\' must be valuable');
      }
    };

    self.deviceRadio = windowWidth / 750;
  }

  /**
   *
   */
  function observer() {
    var self = this;

    var EVENT_TYPE = ['ready', 'beforeImageLoad', 'beforeDraw', 'imageLoad'];

    self.on = function (event, fn) {
      if (EVENT_TYPE.indexOf(event) > -1) {
        if (typeof fn === 'function') {
          event === 'ready' ? fn(self) : self['on' + firstLetterUpper(event)] = fn;
        }
      } else {
        console.error('event: ' + event + ' is invalid');
      }
      return self;
    };
  }

  /**
   * Created by sail on 2017/6/11.
   */
  function methods() {
    var self = this;

    var deviceRadio = self.deviceRadio;

    var boundWidth = self.width; // 裁剪框默认宽度,即整个画布宽度
    var boundHeight = self.height; // 裁剪框默认高度,即整个画布高度
    var _self$cut = self.cut,
      _self$cut$x = _self$cut.x,
      x = _self$cut$x === undefined ? 0 : _self$cut$x,
      _self$cut$y = _self$cut.y,
      y = _self$cut$y === undefined ? 0 : _self$cut$y,
      _self$cut$width = _self$cut.width,
      width = _self$cut$width === undefined ? boundWidth : _self$cut$width,
      _self$cut$height = _self$cut.height,
      height = _self$cut$height === undefined ? boundHeight : _self$cut$height;


    self.updateCanvas = function () {
      if (self.croperTarget) {
        //  画布绘制图片
        self.ctx.drawImage(self.croperTarget, self.imgLeft, self.imgTop, self.scaleWidth, self.scaleHeight);
      }
      typeof self.onBeforeDraw === 'function' && self.onBeforeDraw(self.ctx, self);

      self.setBoundStyle(); //	设置边界样式
      self.ctx.draw();
      return self;
    };

    self.pushOrign = function (src) {
      self.src = src;

      typeof self.onBeforeImageLoad === 'function' && self.onBeforeImageLoad(self.ctx, self);

      wx.getImageInfo({
        src: src,
        success: function success(res) {
          var innerAspectRadio = res.width / res.height;

          self.croperTarget = res.path;

          // console.log(x, y);
          if (innerAspectRadio < width / height) {
            self.rectX = x;
            self.baseWidth = width;
            self.baseHeight = width / innerAspectRadio;
            self.rectY = y - Math.abs((height - self.baseHeight) / 2);
          } else {
            self.rectY = y;
            self.baseWidth = height * innerAspectRadio;
            self.baseHeight = height;
            self.rectX = x - Math.abs((width - self.baseWidth) / 2);
          }

          self.imgLeft = self.rectX;
          self.imgTop = self.rectY;
          self.scaleWidth = self.baseWidth;
          self.scaleHeight = self.baseHeight;

          self.updateCanvas();

          typeof self.onImageLoad === 'function' && self.onImageLoad(self.ctx, self);
        }
      });

      self.update();
      return self;
    };

    self.getCropperImage = function () {
      for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var id = self.id;

      var ARG_TYPE = toString.call(args[0]);

      switch (ARG_TYPE) {
        case '[object Object]':
          var _args$0$quality = args[0].quality,
            quality = _args$0$quality === undefined ? 10 : _args$0$quality;


          if (typeof quality !== 'number') {
            console.error('quality\uFF1A' + quality + ' is invalid');
          } else if (quality < 0 || quality > 10) {
            console.error('quality should be ranged in 0 ~ 10');
          }
          wx.canvasToTempFilePath({
            canvasId: id,
            x: x,
            y: y,
            width: width,
            height: height,
            destWidth: width * quality / (deviceRadio * 10),
            destHeight: height * quality / (deviceRadio * 10),
            success: function success(res) {
              typeof args[args.length - 1] === 'function' && args[args.length - 1](res.tempFilePath);
            }
          }); break;
        case '[object Function]':
          wx.canvasToTempFilePath({
            canvasId: id,
            x: x,
            y: y,
            width: width,
            height: height,
            destWidth: width / deviceRadio,
            destHeight: height / deviceRadio,
            success: function success(res) {
              typeof args[args.length - 1] === 'function' && args[args.length - 1](res.tempFilePath);
            }
          }); break;
      }

      return self;
    };
  }

  /**
   * Created by sail on 2017/6/11.
   */
  function update() {
    var self = this;

    if (!self.src) return;

    self.__oneTouchStart = function (touch) {
      self.touchX0 = touch.x;
      self.touchY0 = touch.y;
    };

    self.__oneTouchMove = function (touch) {
      var xMove = void 0,
        yMove = void 0;
      //计算单指移动的距离
      if (self.touchended) {
        return self.updateCanvas();
      }
      xMove = touch.x - self.touchX0;
      yMove = touch.y - self.touchY0;

      var imgLeft = self.rectX + xMove;
      var imgTop = self.rectY + yMove;

      self.outsideBound(imgLeft, imgTop);

      self.updateCanvas();
    };

    self.__twoTouchStart = function (touch0, touch1) {
      var xMove = void 0,
        yMove = void 0,
        oldDistance = void 0;

      self.touchX1 = self.rectX + self.scaleWidth / 2;
      self.touchY1 = self.rectY + self.scaleHeight / 2;

      //计算两指距离
      xMove = touch1.x - touch0.x;
      yMove = touch1.y - touch0.y;
      oldDistance = Math.sqrt(xMove * xMove + yMove * yMove);

      self.oldDistance = oldDistance;
    };

    self.__twoTouchMove = function (touch0, touch1) {
      var xMove = void 0,
        yMove = void 0,
        newDistance = void 0;
      var scale = self.scale,
        zoom = self.zoom;
      // 计算二指最新距离

      xMove = touch1.x - touch0.x;
      yMove = touch1.y - touch0.y;
      newDistance = Math.sqrt(xMove * xMove + yMove * yMove);

      //  使用0.005的缩放倍数具有良好的缩放体验
      self.newScale = self.oldScale + 0.001 * zoom * (newDistance - self.oldDistance);

      //  设定缩放范围
      self.newScale <= 1 && (self.newScale = 1);
      self.newScale >= scale && (self.newScale = scale);

      self.scaleWidth = self.newScale * self.baseWidth;
      self.scaleHeight = self.newScale * self.baseHeight;
      var imgLeft = self.touchX1 - self.scaleWidth / 2;
      var imgTop = self.touchY1 - self.scaleHeight / 2;

      self.outsideBound(imgLeft, imgTop);

      self.updateCanvas();
    };

    self.__xtouchEnd = function () {
      self.oldScale = self.newScale;
      self.rectX = self.imgLeft;
      self.rectY = self.imgTop;
    };
  }

  /**
   * Created by sail on 2017/6/11.
   */

  var handle = {
    //  图片手势初始监测
    touchStart: function touchStart(e) {
      var self = this;

      var _e$touches = slicedToArray(e.touches, 2),
        touch0 = _e$touches[0],
        touch1 = _e$touches[1];

      setTouchState(self, true, null, null);

      //计算第一个触摸点的位置,并参照改点进行缩放
      self.__oneTouchStart(touch0);

      // 两指手势触发
      if (e.touches.length >= 2) {
        self.__twoTouchStart(touch0, touch1);
      }
    },


    //  图片手势动态缩放
    touchMove: function touchMove(e) {
      var self = this;

      var _e$touches2 = slicedToArray(e.touches, 2),
        touch0 = _e$touches2[0],
        touch1 = _e$touches2[1];

      setTouchState(self, null, true);

      // 单指手势时触发
      if (e.touches.length === 1) {
        self.__oneTouchMove(touch0);
      }
      // 两指手势触发
      if (e.touches.length >= 2) {
        self.__twoTouchMove(touch0, touch1);
      }
    },
    touchEnd: function touchEnd(e) {
      var self = this;

      setTouchState(self, false, false, true);
      self.__xtouchEnd();
    }
  };

  /**
   * Created by sail on 1017/6/12.
   */
  function cut() {
    var self = this;
    var deviceRadio = self.deviceRadio;

    var boundWidth = self.width; // 裁剪框默认宽度,即整个画布宽度
    var boundHeight = self.height;
    // 裁剪框默认高度,即整个画布高度
    var _self$cut = self.cut,
      _self$cut$x = _self$cut.x,
      x = _self$cut$x === undefined ? 0 : _self$cut$x,
      _self$cut$y = _self$cut.y,
      y = _self$cut$y === undefined ? 0 : _self$cut$y,
      _self$cut$width = _self$cut.width,
      width = _self$cut$width === undefined ? boundWidth : _self$cut$width,
      _self$cut$height = _self$cut.height,
      height = _self$cut$height === undefined ? boundHeight : _self$cut$height;

    /**
    * 设置边界
    * @param imgLeft 图片左上角横坐标值
    * @param imgTop 图片左上角纵坐标值
    */

    self.outsideBound = function (imgLeft, imgTop) {
      self.imgLeft = imgLeft >= x ? x : self.scaleWidth + imgLeft - x <= width ? x + width - self.scaleWidth : imgLeft;

      self.imgTop = imgTop >= y ? y : self.scaleHeight + imgTop - y <= height ? y + height - self.scaleHeight : imgTop;
    };

    /**
    * 设置边界样式
    * @param color	边界颜色
    */
    self.setBoundStyle = function () {
      var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref$color = _ref.color,
        color = _ref$color === undefined ? '#04b00f' : _ref$color,
        _ref$mask = _ref.mask,
        mask = _ref$mask === undefined ? 'rgba(0, 0, 0, 0.3)' : _ref$mask,
        _ref$lineWidth = _ref.lineWidth,
        lineWidth = _ref$lineWidth === undefined ? 1 : _ref$lineWidth;

      // 绘制半透明层
      self.ctx.beginPath();
      self.ctx.setFillStyle(mask);
      self.ctx.fillRect(0, 0, x, boundHeight);
      self.ctx.fillRect(x, 0, width, y);
      self.ctx.fillRect(x, y + height, width, boundHeight - y - height);
      self.ctx.fillRect(x + width, 0, boundWidth - x - width, boundHeight);
      self.ctx.fill();

      // 设置边界左上角样式
      // 为使边界样式处于边界外边缘,此时x、y均要减少lineWidth
      self.ctx.beginPath();
      self.ctx.setStrokeStyle(color);
      self.ctx.setLineWidth(lineWidth);
      self.ctx.moveTo(x - lineWidth, y + 10 - lineWidth);
      self.ctx.lineTo(x - lineWidth, y - lineWidth);
      self.ctx.lineTo(x + 10 - lineWidth, y - lineWidth);
      self.ctx.stroke();

      // 设置边界左下角样式
      // 为使边界样式处于边界外边缘,此时x要减少lineWidth、y要增加lineWidth
      self.ctx.beginPath();
      self.ctx.setStrokeStyle(color);
      self.ctx.setLineWidth(lineWidth);
      self.ctx.moveTo(x - lineWidth, y + height - 10 + lineWidth);
      self.ctx.lineTo(x - lineWidth, y + height + lineWidth);
      self.ctx.lineTo(x + 10 - lineWidth, y + height + lineWidth);
      self.ctx.stroke();

      // 设置边界右上角样式
      // 为使边界样式处于边界外边缘,此时x要增加lineWidth、y要减少lineWidth
      self.ctx.beginPath();
      self.ctx.setStrokeStyle(color);
      self.ctx.setLineWidth(lineWidth);
      self.ctx.moveTo(x + width - 10 + lineWidth, y - lineWidth);
      self.ctx.lineTo(x + width + lineWidth, y - lineWidth);
      self.ctx.lineTo(x + width + lineWidth, y + 10 - lineWidth);
      self.ctx.stroke();

      // 设置边界右下角样式
      // 为使边界样式处于边界外边缘,此时x、y均要增加lineWidth
      self.ctx.beginPath();
      self.ctx.setStrokeStyle(color);
      self.ctx.setLineWidth(lineWidth);
      self.ctx.moveTo(x + width + lineWidth, y + height - 10 + lineWidth);
      self.ctx.lineTo(x + width + lineWidth, y + height + lineWidth);
      self.ctx.lineTo(x + width - 10 + lineWidth, y + height + lineWidth);
      self.ctx.stroke();
    };
  }

  var weCropper = function () {
    function weCropper(params) {
      classCallCheck(this, weCropper);

      var self = this;
      var _default = {};

      validator(self, DEFAULT);

      Object.keys(DEFAULT).forEach(function (key) {
        _default[key] = DEFAULT[key].default;
      });
      Object.assign(self, _default, params);

      self.prepare();
      self.attachPage();
      self.createCtx();
      self.observer();
      self.cutt();
      self.methods();
      self.init();
      self.update();

      return self;
    }

    createClass(weCropper, [{
      key: 'init',
      value: function init() {
        var self = this;
        var src = self.src;


        self.version = version;

        typeof self.onReady === 'function' && self.onReady(self.ctx, self);

        if (src) {
          self.pushOrign(src);
        }
        setTouchState(self, false, false, false);

        self.oldScale = 1;
        self.newScale = 1;

        return self;
      }
    }]);
    return weCropper;
  }();

  Object.assign(weCropper.prototype, handle);

  weCropper.prototype.prepare = prepare;
  weCropper.prototype.observer = observer;
  weCropper.prototype.methods = methods;
  weCropper.prototype.cutt = cut;
  weCropper.prototype.update = update;

  return weCropper;

})));

本地上传显示获取到的图片
  <image src="{{src}}" class="avatar {{bgcss}}"></image>

在页面加载时判断是否返回参数,若是从upload页面跳转回来,会携带图片参数,这时赋值给事先设定好的src参数,前端获取到后进行显示

 onLoad: function (options) {
    var that = this
    
    that.setData({
      bgPic: that.data.imgs[0],
    })
    let { avatar } = options;
    if (avatar) {
      that.setData({
        src: avatar
      });
    }
    console.log(this.data.src)
  },
用canvas绘制头像框和头像

canvas定义

        <view style='position:absolute;left:400rpx;'><canvas  canvas-id='ahaucanvas' style='height:840px;width:840px;position:absolute;left:400rpx;'>
        </canvas></view> 

点击下一步之后,进行canvas的绘制以及参数的传递
将背景图从云存储名称转换为本地临时路径,方便canvas进行绘制,跳转到draw函数进行绘制

  //下一步按钮函数,跳转界面
  bindViewTap: function() {
    var that=this;
    app.globalData.bgPic=this.data.bgPic;
    wx.getImageInfo({
      src:that.data.bgPic,
      success: res => {
        that.data.bgPic=res.path
        console.log(that.data.bgPic+"地址")
        that.draw();
      }
    })
  }

将两个图片绘制在一起,并且获取到最后的图片路径,跳转下一个界面
因为这是参考了别人的代码,所以参数方面需要修改,导致下一张获取到的图片头像位置不太对,目前还在调整中

draw(){
    var self = this;
    var contex = wx.createCanvasContext('ahaucanvas'); //ttcanvas为该canvas的ID
    //var contex = ctx.getContext('2d');
    var avatarurl_width = 840; //这个是画布宽
    var avatarurl_heigth = 840; //这个是高
    // var avatarurl_x = 50;
    // var avatarurl_y = 50;
    // contex.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);//这个地方我画了个头像的圆
    // contex.clip();
    contex.drawImage(self.data.src, 127, 120);
    contex.restore();
    contex.save();
    contex.beginPath(); //开始绘制
    // contex.arc(150, 50, 30, 0, Math.PI * 2, false);
    // contex.clip();
    //contex.arc(25, 25, 25, Math.PI * 2, false);
    //contex.clip();
    contex.drawImage(self.data.bgPic, 0, 0, avatarurl_width, avatarurl_heigth); // 这个是我的背
    contex.restore();
    // contex.setFontSize(20)
    // contex.fillStyle = "#fff";
    // contex.fillText(self.data.gameConfig.myScore, 130, 132)
    // contex.restore();
    contex.draw(true, setTimeout(function() {
      wx.canvasToTempFilePath({ 
        width: 840,
        height: 840,
        destWidth: 840,
        destHeight: 840,
        canvasId: 'ahaucanvas',
        success: res => {
          var tempFilePath = res.tempFilePath;
       wx.navigateTo({
          url:  `../decorate/decorate?index=${tempFilePath}`
        })
        }
      }, this)
    }, 100))
   }
头饰选择界面设计

首先是页面设计,分为背景图,头像框显示部分,下方的头饰选择部分,虚线框部分根据用户操作可以进行移动,放大缩小。目前为测试,所以先使用了圣诞帽来测试。以及下方的下一步,跳转到保存头像界面,
在这里插入图片描述

<view class="container">
<!-- 背景 -->
<image class='background' src="../../image/bg3.png" mode="aspectFill"></image>

<view  wx:if="{{!combine}}">
    <view class="container1" 
          id="container"
          bind:touchstart="touchStart" 
          bind:touchend="touchEnd"
          bind:touchmove="touchMove">
    <!-- 头像框 -->
<view class="img_head">
<image src="{{index}}"></image>
</view>
 <!--下方两个按钮-->
<button class="btn-go" bindtap="combinePic" style="margin-top:280rpx;">
  <image src="cloud://yunkaifa-fp3py.7975-yunkaifa-fp3py-1303879667/圣诞/next2.png"></image>
</button>

    <icon type="cancel" class="cancel" id="cancel"
            style="top:{{cancelCenterY-10+'px'}};left:{{cancelCenterX-10+'px'}};display:{{check}}"></icon>
    <icon type="waiting" class="handle"  id="handle"  color="green"
            style="top:{{handleCenterY-10+'px'}};left:{{handleCenterX-10+'px'}};display:{{check}}"></icon>
    <image class="hat" id='hat' src="../../image/{{currentHatId}}.png"
    style="top:{{hatCenterY-hatSize/2-2+'px'}};left:{{hatCenterX-hatSize/2-2+'px'}};transform:rotate({{rotate+'deg'}}) scale({{scale}});display:{{check}}"
    ></image>
    </view>
    
    <image src="../../image/white.png" style="width:100%;height:180rpx;position:absolute;margin-top:21rpx"></image>
   <scroll-view class="scrollView" scroll-x="true">
    <image class="imgList" 
        wx:for="...imgList" wx:key="{{index+1}}" 
        src="../../image/{{index+1}}.png"
        data-hat-id="{{index+1}}"
        bind:tap="chooseImg"></image>
  </scroll-view> 
</view>
</view>

.background {
  width: 100%;
  min-height:100%;
  position:fixed; 
  background-size:100% 100%;
  z-index: -1;
}
.img_down{
  margin-top: 403rpx;
  position: absolute;
  left:13.5%;
}
.img_down image{
  height:550rpx;
  width: 550rpx;
}
.img_head{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  z-index: 0;
  margin-top: 65px;
}
.img_head image{
  height: 270px;
  width: 270px;
}
.btn-go{
  background: rgba(0,0,0,0);
  width: 420rpx;
  height: 75rpx;
  padding: 0;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.btn-go image{
  width: 420rpx;
  height: 75rpx;
}
.btn-go::after{
  border: 0;
}



.container1{
  height:270px;
  width:100%;
}
.bg{
  z-index:0;
  height: 270px;
  width:270px;
}
.hat{ 
  height: 100px;
  width: 100px;
  position: absolute;
  border: dashed 4rpx red;
  top:100px;
}
.handle,.cancel{
  position: absolute;
  z-index: 1;
  width:20px;
  height:20px;
}
.scrollView{
   width: 100%; 
   white-space: nowrap;
   margin-top: 30rpx;
}
.imgList{
  height: 140rpx;
  width: 140rpx;
  border:2rpx solid;
  margin: 10rpx;
}
显示上个页面传递的图片
   wx.navigateTo({
          url:  `../decorate/decorate?index=${tempFilePath}`
        })
<view class="img_head">
<image src="{{index}}"></image>
</view>
et { index } = options;
      that.setData({
        index: index,
        bgPic: app.globalData.bgPic
      })
头饰放置部分
1.左上方去除头饰点击事件

给该组件添加一个display样式,通过控制其的样式决定展示与否

    <icon type="cancel" class="cancel" id="cancel"
            style="top:{{cancelCenterY-10+'px'}};left:{{cancelCenterX-10+'px'}};display:{{check}}"></icon>
    <icon type="waiting" class="handle"  id="handle"  color="green"
            style="top:{{handleCenterY-10+'px'}};left:{{handleCenterX-10+'px'}};display:{{check}}"></icon>
    <image class="hat" id='hat' src="../../image/{{currentHatId}}.png"
    style="top:{{hatCenterY-hatSize/2-2+'px'}};left:{{hatCenterX-hatSize/2-2+'px'}};transform:rotate({{rotate+'deg'}}) scale({{scale}});display:{{check}}"
    ></image>

触摸开始函数,判断当前的焦点在哪,若在×的icon上,那么修改其样式为none,头饰不显示
若点击下方的头饰进行选择,那么需要将上方的头饰预览进行显示,样式修改为block

touchStart(e){
      if(e.target.id=="hat"){
        this.touch_target="hat";
      }else if(e.target.id=="handle"){
        this.touch_target="handle"
      }else{
        this.touch_target=""
      };
      
      if(this.touch_target!=""){
        this.start_x=e.touches[0].clientX;
        this.start_y=e.touches[0].clientY;
      }else{
        this.setData({
          check :'none'
        })
      }
    },
    chooseImg(e){

      this.setData({
        currentHatId:e.target.dataset.hatId,
        check :'block'
      })
    },
2.右下角头饰放大缩小响应事件以及移动事件

触摸开始事件判断当前焦点是否在放大缩小icon上或者在头饰图片上,若是,则获取当前的触摸位置

touchStart(e){
      if(e.target.id=="hat"){
        this.touch_target="hat";
      }else if(e.target.id=="handle"){
        this.touch_target="handle"
      }else{
        this.touch_target=""
      };
      
      if(this.touch_target!=""){
        this.start_x=e.touches[0].clientX;
        this.start_y=e.touches[0].clientY;
      }else{
        this.setData({
          check :'none'
        })
      }
    },

触摸移动事件
判断为放大缩小icon上还是自头饰图片上,进行计算并且设置头像图片的参数,使其页面中变化

  touchMove(e){
        var current_x=e.touches[0].clientX;
        var current_y=e.touches[0].clientY;
        var moved_x=current_x-this.start_x;
        var moved_y=current_y-this.start_y;
        if(this.touch_target=="hat"){
          this.setData({
            hatCenterX:this.data.hatCenterX+moved_x,
            hatCenterY:this.data.hatCenterY+moved_y,
            cancelCenterX:this.data.cancelCenterX+moved_x,
            cancelCenterY:this.data.cancelCenterY+moved_y,
            handleCenterX:this.data.handleCenterX+moved_x,
            handleCenterY:this.data.handleCenterY+moved_y
          })
        };
        if(this.touch_target=="handle"){
          this.setData({
            handleCenterX:this.data.handleCenterX+moved_x,
            handleCenterY:this.data.handleCenterY+moved_y,
            cancelCenterX:2*this.data.hatCenterX-this.data.handleCenterX,
            cancelCenterY:2*this.data.hatCenterY-this.data.handleCenterY
          });
          let diff_x_before=this.handle_center_x-this.hat_center_x;
          let diff_y_before=this.handle_center_y-this.hat_center_y;
          let diff_x_after=this.data.handleCenterX-this.hat_center_x;
          let diff_y_after=this.data.handleCenterY-this.hat_center_y;
          let distance_before=Math.sqrt(diff_x_before*diff_x_before+diff_y_before*diff_y_before);
          let distance_after=Math.sqrt(diff_x_after*diff_x_after+diff_y_after*diff_y_after);
          let angle_before=Math.atan2(diff_y_before,diff_x_before)/Math.PI*180;
          let angle_after=Math.atan2(diff_y_after,diff_x_after)/Math.PI*180;
          this.setData({
            scale:distance_after/distance_before*this.scale,
            rotate:angle_after-angle_before+this.rotate,
          })
        }
        this.start_x=current_x;
        this.start_y=current_y;
    },
下方头饰选择部分

滚动方式展示头饰图片,点击将选择的图片同步到上方的头饰预览上
使用list,利用其下标给图片赋值id和决定显示哪张图片
只需要将点击的图片id赋值给上方的头饰预览的图片id即可

    chooseImg(e){

      this.setData({
        currentHatId:e.target.dataset.hatId,
        check :'block'
      })
    },
头饰选择部分的下一步

将头饰的位置信息存入全部变量中,方便后一个页面调用进行绘制

 combinePic(){
      var that=this;
      var index=that.data.index; 


      app.globalData.scale=this.scale;
      app.globalData.rotate = this.rotate;
      app.globalData.hat_center_x = this.hat_center_x;
      app.globalData.hat_center_y = this.hat_center_y;
      app.globalData.currentHatId = this.data.currentHatId;


      wx.navigateTo({
        url: '../logs/logs?index=' + index
      })
    }
绘制背景图片以及头饰

使用canvas绘制

  <canvas  class="myCanvas" canvas-id="myCanvas" style="height:270px;;width:100%;margin-top: 440rpx;"/>

获取全局变量中的头饰位置参数,进行计算后绘制在canvas上

draw() {
      let scale = app.globalData.scale;
      let rotate = app.globalData.rotate;
      let hat_center_x = app.globalData.hat_center_x;
      let hat_center_y = app.globalData.hat_center_y-65;
      let currentHatId = app.globalData.currentHatId;
      const pc = wx.createCanvasContext('myCanvas');
      const windowWidth = wx.getSystemInfoSync().windowWidth;
      const hat_size = 100 * scale;
  
  
      pc.clearRect(0, 0, windowWidth, 270);
      pc.drawImage(this.bgPic, windowWidth / 2 - 135, 0, 270, 270);
      pc.translate(hat_center_x,hat_center_y);
      pc.rotate(rotate * Math.PI / 180);
      pc.drawImage("../../image/" + currentHatId + ".png", -hat_size / 2, -hat_size / 2, hat_size, hat_size);
      pc.draw();
    },

保存图片

参数还未修改,可能导致导出的图片像素太小,之后再调整

    savePic() {
      const windowWidth = wx.getSystemInfoSync().windowWidth;
      wx.canvasToTempFilePath({
        x: windowWidth / 2 - 150,
        y: 0,
        height: 300,
        width: 300,
        canvasId: 'myCanvas',
        success: (res) => {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: (res) => {
              wx.navigateTo({
                url: '../index/index',
                success: function(res) {},
                fail: function(res) {},
                complete: function(res) {},
              })
              console.log("success:" + res);
            }, fail(e) {
              console.log("err:" + e);
            }
          })
        }
      });
    }

以上功能还有些需要改进的地方,例如参数调节,多个头像框和头像之间的适配关系,canvas绘制问题等,之后再进行修改

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值