当前位置: 首页 » 笔记 » 微信小程序单指、双指操作图片/层(移动缩放)正文

微信小程序单指、双指操作图片/层(移动缩放)

  • 零分
  • 3,115

微信小程序单指、双指操作图片/层WXML:

<view class="myCanvas">
            <image src="{{ loadSrc}}" class="img" bindtouchstart="touchstartCallback" bindtouchmove="touchmoveCallback" bindload="imgload" style="width: {{ scaleWidth  }}px;height: {{ scaleHeight }}px;margin-top:{{marginTop}}px;margin-left:{{marginLeft}}px;" />
        </view>

微信小程序单指、双指操作图片/层JS:

/**
   * 监听图片加载成功时触发
   */
  imgload: function (e) {
    this.multiple = e.detail.width / this.width; // 计算原图和默认显示的倍数
    let height = this.multiple > 1 ? e.detail.height / this.multiple : e.detail.height; // 等比例计算出默认高度
    let width = this.multiple > 1 ? this.width : e.detail.width;
    this.setData({
      baseWidth: e.detail.width, // 获取图片实际宽度
      baseHeight: e.detail.height, // 获取图片实际高度
      initWidth: width,
      initHeight: height,
      scaleWidth: width,
      scaleHeight: height,
    })
  },
  /**
   * 双手指触发开始 计算开始触发两个手指坐标的距离
   */
  touchstartCallback: function (e) {
    // 单手指缩放开始,不做任何处理
    if (e.touches.length == 1) {
        lastTouchPoint = { x: 0, y: 0 }        
        return
    };
    let distance = this.calcDistance(e.touches[0], e.touches[1]);
    this.setData({
      'distance': distance,
    })
    
  },
  /**
   * 双手指移动   计算两个手指坐标和距离
   */
  touchmoveCallback: function (e) {
    // 单手指缩放不做任何操作
    if (e.touches.length == 1) {
        if (lastTouchPoint.x == 0 && lastTouchPoint.y == 0) {
            lastTouchPoint.x = e.touches[0].clientX
            lastTouchPoint.y = e.touches[0].clientY
          } else {
            var xOffset = e.touches[0].clientX - lastTouchPoint.x
            var yOffset = e.touches[0].clientY - lastTouchPoint.y
            this.setData({
              marginTop: this.data.marginTop + yOffset,
              marginLeft: this.data.marginLeft + xOffset,
            })
            lastTouchPoint.x = e.touches[0].clientX
            lastTouchPoint.y = e.touches[0].clientY
        }
        return
    };
    let distance = this.calcDistance(e.touches[0], e.touches[1]);
    // 计算移动的过程中实际移动了多少的距离
    let distanceDiff = distance - this.data.distance;
    let newScale = this.data.scale + 0.005 * distanceDiff;
    
   
    // 最小缩放到0.5
    if (newScale <= 0.5) {
      newScale = 0.5;
    };
 
    let scaleWidth = newScale * this.data.initWidth;
    let scaleHeight = newScale * this.data.initHeight;
    this.setData({
      distance: distance,
      scale: newScale,
      scaleWidth: scaleWidth,
      scaleHeight: scaleHeight,
      diff: distanceDiff
    });
  },
 
  /**
   * 计算两个手指距离
   */
  calcDistance(pos0, pos1) {
    let xMove = pos1.clientX - pos0.clientX;
    let yMove = pos1.clientY - pos0.clientY;
    return (Math.sqrt(xMove * xMove + yMove * yMove));
  },

声明:博客中如无特殊说明或标注的文章均为博客原创文章,部分文章来源互联网,如有侵犯您的版权,或者对零分博客发布的文章有异议,请来信告知删除、修改,如您有好的建议或者意见也可以来信,谢谢!

请TA喝杯水^_^ 如本文“对您有用”,欢迎随意打赏,让我们坚持创作! 请TA喝水