当前位置:首页 > VUE

vue实现移动轨迹

2026-03-08 22:46:29VUE

Vue 实现移动轨迹

在 Vue 中实现移动轨迹可以通过监听鼠标或触摸事件,记录移动路径并实时渲染。以下是具体实现方法:

监听事件并记录坐标

使用 @mousemove@touchmove 事件监听移动动作,将坐标点存入数组:

vue实现移动轨迹

<template>
  <div 
    @mousemove="handleMove"
    @touchmove="handleTouchMove"
    ref="container"
  >
    <svg width="100%" height="100%">
      <path :d="pathData" fill="none" stroke="blue" stroke-width="2"/>
    </svg>
  </div>
</template>

<script>
export default {
  data() {
    return {
      points: [],
      isDrawing: false
    }
  },
  computed: {
    pathData() {
      if (this.points.length < 2) return '';
      return `M ${this.points[0].x} ${this.points[0].y} L ${this.points.map(p => `${p.x} ${p.y}`).join(' L ')}`;
    }
  },
  methods: {
    handleMove(e) {
      if (!this.isDrawing) return;
      const rect = this.$refs.container.getBoundingClientRect();
      this.points.push({
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      });
    },
    handleTouchMove(e) {
      if (!this.isDrawing) return;
      const rect = this.$refs.container.getBoundingClientRect();
      const touch = e.touches[0];
      this.points.push({
        x: touch.clientX - rect.left,
        y: touch.clientY - rect.top
      });
    }
  }
}
</script>

平滑轨迹处理

添加插值算法使轨迹更平滑,例如使用贝塞尔曲线:

computed: {
  pathData() {
    if (this.points.length < 3) return '';
    let path = `M ${this.points[0].x} ${this.points[0].y}`;
    for (let i = 1; i < this.points.length - 2; i++) {
      const xc = (this.points[i].x + this.points[i + 1].x) / 2;
      const yc = (this.points[i].y + this.points[i + 1].y) / 2;
      path += ` Q ${this.points[i].x} ${this.points[i].y}, ${xc} ${yc}`;
    }
    return path;
  }
}

性能优化

对于高频移动事件,使用防抖或节流控制更新频率:

vue实现移动轨迹

import { throttle } from 'lodash';

methods: {
  handleMove: throttle(function(e) {
    // 处理逻辑
  }, 16), // 约60fps
}

清除轨迹

添加重置功能清除已有轨迹:

methods: {
  clearPath() {
    this.points = [];
  }
}

移动端适配

确保触摸事件正常工作:

<div
  @touchstart="isDrawing = true"
  @touchend="isDrawing = false"
  @touchcancel="isDrawing = false"
></div>

通过以上方法可以实现基本的移动轨迹记录和展示功能,可根据实际需求扩展轨迹样式、存储或分析功能。

标签: 轨迹vue
分享给朋友:

相关文章

vue实现付款

vue实现付款

Vue 实现付款功能 在 Vue 中实现付款功能通常需要集成第三方支付网关(如支付宝、微信支付、Stripe 等)。以下是常见的实现方法: 集成支付宝/微信支付 安装必要的依赖(如 axios 用于…

vue实现drag

vue实现drag

Vue 实现拖拽功能的方法 在 Vue 中实现拖拽功能可以通过原生 HTML5 的拖拽 API 或第三方库如 vuedraggable 来完成。以下是两种常见方法的实现方式。 使用 HTML5 拖拽…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

vue实现看板

vue实现看板

Vue 实现看板功能 使用 Vue 实现看板功能可以通过组件化开发、状态管理和拖拽库结合完成。以下是一个完整的实现方案: 基础项目结构 src/ ├── components/ │ ├── Ka…

vue单选实现

vue单选实现

Vue 单选实现 在 Vue 中实现单选功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 绑定单选按钮 通过 v-model 绑定一个变量,可以实现单选效果。当用户选择不同的选…

vue实现分步

vue实现分步

Vue 实现分步功能 在 Vue 中实现分步功能可以通过多种方式完成,以下是几种常见的方法: 使用动态组件 通过动态组件切换不同的步骤内容,结合 v-if 或 component 标签实现分步逻辑。…