vue怎么实现canvas的触摸滚动画布的功能(提供两种方案)

方法(一):使用组件内置的getGraph().translate方法

(1)html部分

  <template>
    <div
          class="vfe-chart-main"
          @touchstart.passive="handleTouchStart"
          @touchmove.passive="handleTouchMove"
        >
          <!-- 画布内容 -->
          <flow
            ref="flow"
          />  
      </div>
  </template>

(2)methods方法部分

<script>
  methods:{
   handleTouchStart(event) {
        console.log("handleTouchStart");
        this.startX = event.touches[0].clientX;
        this.startY = event.touches[0].clientY;
      },

  handleTouchMove(event) {
        console.log("handleTouchMove");
        const moveX = event.touches[0].clientX - this.startX;
        const moveY = event.touches[0].clientY - this.startY;
        this.$refs.flow.getGraph().translate(moveX, moveY);
        this.startX = event.touches[0].clientX;
        this.startY = event.touches[0].clientY;
      },
  }
</script>

方法(二):在最外层div添加ref属性,利用原生的方法解决

(1)html部分

<template>   
  <div
          class="vfe-chart-main"
          @touchstart.passive="handleTouchStart"
          @touchmove.passive="handleTouchMove"
          ref="flowContainer"
        >
          <!-- 画布内容 -->
          <flow
            ref="flow"
          />
     </div>
</template>

(2)methods方法部分

<script>   
  methods:{
    handleTouchMove(event) {
      console.log("handleTouchMove111");
      // 防止默认的滚动行为
      event.preventDefault();

      // 计算触摸点的当前位置与开始位置之间的差异
      const moveX = event.touches[0].clientX - this.startX;
      const moveY = event.touches[0].clientY - this.startY;

      // 更新组件的位置
      const el = this.$refs.flowContainer;
      const currentTransform = window.getComputedStyle(el).transform;
      let matrix = currentTransform === 'none' 
        ? [1, 0, 0, 1, 0, 0] // 默认矩阵
        : currentTransform.split('(')[1].split(')')[0].split(',');
      const translateX = parseInt(matrix[4]) + moveX;
      const translateY = parseInt(matrix[5]) + moveY;

      el.style.transform = `translate(${translateX}px, ${translateY}px)`;

      // 更新起始坐标为当前坐标,以便下一次计算
      this.startX = event.touches[0].clientX;
      this.startY = event.touches[0].clientY;
    },
  }
</script>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值