当前位置:首页 > 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实现ai

vue实现ai

Vue 实现 AI 功能 Vue.js 可以通过集成第三方 AI 服务或本地 AI 模型来实现 AI 功能。以下是几种常见的方法: 集成第三方 AI API 使用 Vue 调用如 OpenAI、Go…

vue实现公告

vue实现公告

Vue 实现公告功能的方法 公告功能通常需要实现滚动展示、自动切换或固定显示的效果。以下是几种常见的实现方式: 使用 marquee 标签实现滚动公告 <template> <…

vue实现波形

vue实现波形

实现波形效果的方法 在Vue中实现波形效果可以通过多种方式完成,常见的方法包括使用Canvas绘制、CSS动画或第三方库。以下是几种实现方案: 使用Canvas绘制波形 通过Canvas API动态…

vue动画实现

vue动画实现

Vue动画实现方法 Vue提供了多种方式实现动画效果,主要通过内置组件和第三方库完成。 使用<transition>组件 Vue内置的<transition>组件可以为元素添…

实现vue cli

实现vue cli

安装 Vue CLI 确保系统中已安装 Node.js(版本建议 12.x 或更高)。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 安装完成后验证版本:…

vue滑块实现

vue滑块实现

Vue滑块实现方法 使用原生HTML5 range input Vue中可以绑定原生HTML5的range类型input元素实现基础滑块功能: <template> <div&…