0
点赞
收藏
分享

微信扫一扫

使用 Vue3 和 Canvas 实现可交互的波线段图

小安子啊 03-24 12:00 阅读 13

本文将介绍如何使用 Vue3 和 Canvas 实现一个可交互的波线段图,包括绘制波形、放大缩小、单指拖动等功能

  1. 项目设置 首先,使用 Vue CLI 创建一个新的 Vue3 项目:

vue create waveform-viewer 然后,安装依赖:

cd waveform-viewer npm install 2. 创建 Canvas 组件 在 src/components/ 目录下创建一个新的组件 WaveformCanvas.vue:

<template> <canvas ref="canvas" @mousedown="onMouseDown" @mousemove="onMouseMove" @mouseup="onMouseUp" @wheel="onWheel"></canvas> </template>

<script> export default { name: 'WaveformCanvas', data() { return { canvas: null, ctx: null, width: 0, height: 0, scale: 1.0, offsetX: 0, isDragging: false, startX: 0, waveformData: [], // 假设这是你的波形数据 }; }, mounted() { this.canvas = this.$refs.canvas; this.ctx = this.canvas.getContext('2d'); this.width = this.canvas.width = window.innerWidth; this.height = this.canvas.height = window.innerHeight; this.drawWaveform(); }, methods: { drawWaveform() { this.ctx.clearRect(0, 0, this.width, this.height); this.ctx.strokeStyle = '#00ff00'; this.ctx.lineWidth = 2; this.ctx.beginPath();

  const dataLength = this.waveformData.length;
  const step = this.width / dataLength;

  for (let i = 0; i < dataLength; i++) {
    const x = i * step * this.scale + this.offsetX;
    const y = this.height / 2 + this.waveformData[i] * (this.height / 4);
    if (i === 0) {
      this.ctx.moveTo(x, y);
    } else {
      this.ctx.lineTo(x, y);
    }
  }

  this.ctx.stroke();
},
onMouseDown(event) {
  this.isDragging = true;
  this.startX = event.clientX;
},
onMouseMove(event) {
  if (this.isDragging) {
    const deltaX = event.clientX - this.startX;
    this.offsetX += deltaX;
    this.startX = event.clientX;
    this.drawWaveform();
  }
},
onMouseUp() {
  this.isDragging = false;
},
onWheel(event) {
  event.preventDefault();
  const zoomFactor = 1.1;
  if (event.deltaY < 0) {
    this.scale *= zoomFactor;
  } else {
    this.scale /= zoomFactor;
  }
  this.drawWaveform();
},

}, }; </script>

<style scoped> canvas { display: block; background-color: #000; } </style> 3. 使用组件 在 src/App.vue 中使用 WaveformCanvas 组件:

<template> <div id="app"> <WaveformCanvas /> </div> </template>

<script> import WaveformCanvas from './components/WaveformCanvas.vue';

export default { name: 'App', components: { WaveformCanvas, }, }; </script>

<style> body { margin: 0; overflow: hidden; } </style> 4. 运行项目 现在,你可以运行项目并查看效果:

npm run serve 5. 功能说明 绘制波形:drawWaveform 方法会根据 waveformData 数组中的数据绘制波形。

放大缩小:通过鼠标滚轮事件 onWheel 实现波形的放大和缩小。

单指拖动:通过鼠标事件 onMouseDown、onMouseMove 和 onMouseUp 实现波形的拖动。

  1. 进一步优化 性能优化:对于大数据量的波形,可以考虑使用 requestAnimationFrame 进行优化。

触摸屏支持:可以通过添加触摸事件来支持触摸屏设备。

波形数据加载:可以从文件或 API 加载波形数据,并动态更新 waveformData。

  1. 总结 通过 Vue3 和 Canvas,我们可以轻松实现一个可交互的波线段图。本文介绍了基本的绘制、放大缩小和拖动功能,你可以在此基础上进一步扩展和优化,以满足更多需求。
举报

相关推荐

0 条评论