使用WXS解决touchmove卡顿问题
发布于 4 年前 作者 dduan 978 次浏览 来自 分享

需求描述:

1、可以在图片上写入文字。

2、可以随意拖动文字的位置,并且最终会在拖动后图片对应的位置绘制对应的文字。

开始的做法

1、通过touchmove事件,实时获取x,y轴的位置,实时setData到Data中,然后响应到页面中的输入框元素的top,left。

遇到的问题

1、过于频繁的操作移动,特别是恶意拖动的时候,会卡顿。

解决办法:使用wxs来解决,实现思路,在wxs中定义touch事件,移动时在wxs中先设置输入框的top,left位置。等touchend事件时在把top,left位置同步到页面的事件。相关代码如下

1、在页面目录下创建 页面名.wxs 的文件

2、在wxs文件中编写对应的js代码,在wxs中不能使用let,const,只能使用var定义变量名

// 元素x,y 0 位置跟 鼠标点击位置的距离
var moveX = 0, moveY = 0, x = 0, y = 0

// 开始移动文字
function touchstartByText(e, ownerInstance) {
  moveX = e.changedTouches[0].clientX - e.target.offsetLeft
  moveY = e.changedTouches[0].clientY - e.target.offsetTop
}

// 移动文字中
function touchmoveByText(e, ownerInstance) {
  // 移动图片
  x = e.changedTouches[0].clientX - moveX
  y = e.changedTouches[0].clientY - moveY
  // 控制移动样式
  e.instance.setStyle({
    left: x + 'px',
    top: y + 'px'
  })
}

// 移动位置结束
function touchendByText(e, ownerInstance) {
  if (x > 0 && y > 0) {
    // 操作的下标
    var idx = e.target.dataset.idx || 0
    // 同步页面数据
    ownerInstance.callMethod('touchendByText', {
      idx: idx,
      x: x,
      y: y
    })
  }
}

module.exports = {
  touchstartByText: touchstartByText,
  touchmoveByText: touchmoveByText,
  touchendByText: touchendByText
}

小程序页面的.js文件定义给wxs中调用的函数

// 文字输入框移动结束在页面中js中的操作
touchendByText(data) {
  // 页面中处理的具体逻辑

}

小程序页面中的相关代码

引入wxs文件到页面中
"./ImgComments.wxs" module="move" />

小程序页面中使用wxs中的事件,跟调用js不太一样的地方是需要使用{{}}扩起来,然后用引入的wxs文件定义的module的名称点击函数名。

"{{move.touchstartByText}}"
  bindtouchmove="{{move.touchmoveByText}}"
  bindtouchend="{{move.touchendByText}}"
  bindtap="selTextInput"
  bindinput="textInput"
  data-item="{{item}}"
  data-idx="{{idx}}"
  class="ipt" 
  cursor-spacing="20"
  placeholder="输入内容..."
  placeholder-style="color:{{item.c}}"
  value="{{item.content}}" 
  style="left:{{item.x}}px; top:{{item.y}}px; font-size:{{item.s}}px; color:{{item.c}};">input>
1 回复

坑爹,保存之后,有部分代码丢失了

回到顶部