vue实现心电图
Vue 实现心电图效果
在 Vue 中实现心电图效果通常需要结合 Canvas 或 SVG 进行动态绘制,以下提供两种实现方式:
使用 Canvas 动态绘制
-
创建 Canvas 组件 在 Vue 组件中引入 Canvas 元素,并设置宽度和高度:
<template> <canvas ref="ecgCanvas" width="800" height="200"></canvas> </template> -
初始化 Canvas 上下文 在
mounted生命周期中初始化 Canvas 并设置样式:mounted() { const canvas = this.$refs.ecgCanvas; this.ctx = canvas.getContext('2d'); this.ctx.strokeStyle = 'green'; this.ctx.lineWidth = 2; } -
模拟心电图数据 生成模拟的心电图数据点(正弦波叠加):
generateEcgData() { const points = []; for (let i = 0; i < 800; i++) { const x = i; const y = 100 + Math.sin(i * 0.05) * 30 + Math.random() * 5; points.push({ x, y }); } return points; } -
动画渲染 使用
requestAnimationFrame实现动态绘制:animate() { this.ctx.clearRect(0, 0, 800, 200); const data = this.generateEcgData(); this.ctx.beginPath(); this.ctx.moveTo(data[0].x, data[0].y); for (let i = 1; i < data.length; i++) { this.ctx.lineTo(data[i].x, data[i].y); } this.ctx.stroke(); requestAnimationFrame(this.animate); }
使用 SVG 和动态路径
-
创建 SVG 组件 通过 SVG 的
<path>元素实现平滑曲线:<template> <svg width="800" height="200"> <path :d="pathData" stroke="green" fill="none" stroke-width="2"/> </svg> </template> -
动态生成路径数据 计算 SVG 路径的
d属性:computed: { pathData() { const data = this.generateEcgData(); let d = `M ${data[0].x} ${data[0].y}`; for (let i = 1; i < data.length; i++) { d += ` L ${data[i].x} ${data[i].y}`; } return d; } } -
添加动画效果 使用 Vue 的过渡或 CSS 动画实现移动效果:
path { animation: moveLine 5s linear infinite; } @keyframes moveLine { from { transform: translateX(0); } to { transform: translateX(-100px); } }
真实数据集成
若需对接真实设备数据:
- 通过 WebSocket 或 API 获取实时数据流。
- 使用队列结构维护最新的 100-200 个数据点。
- 在数据更新时触发 Vue 的响应式渲染。
data() {
return {
ecgPoints: [],
};
},
methods: {
updateData(newPoint) {
this.ecgPoints.push(newPoint);
if (this.ecgPoints.length > 200) {
this.ecgPoints.shift();
}
}
}
性能优化建议
-
对于 Canvas 方案,启用
willReadFrequently属性提高渲染效率:this.ctx = canvas.getContext('2d', { willReadFrequently: true }); -
使用
debounce控制高频数据更新的渲染频率。 -
对于静态背景(如网格线),单独使用分层 Canvas 或 SVG
<pattern>减少重绘。
两种方式各有优势:Canvas 适合高性能动态渲染,SVG 更易于实现响应式交互。可根据具体场景选择。






