vue实现心电图
Vue 实现心电图效果
实现心电图效果通常需要结合 Canvas 或 SVG 进行动态绘制,以下是一个基于 Vue 和 Canvas 的实现方案:

安装依赖(如需要)
若使用第三方库(如 chart.js 或 echarts),需先安装:

npm install echarts
基础 Canvas 实现
创建一个 Vue 组件,通过 Canvas 动态绘制心电图折线:
<template>
<div class="ecg-container">
<canvas ref="ecgCanvas" :width="width" :height="height"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
width: 800,
height: 200,
dataPoints: [], // 存储心电图数据
animationId: null,
};
},
mounted() {
this.initData();
this.drawECG();
},
beforeDestroy() {
cancelAnimationFrame(this.animationId);
},
methods: {
initData() {
// 模拟心电图数据(正弦波 + 脉冲)
for (let i = 0; i < 200; i++) {
const x = (i / 10) * Math.PI;
let y = Math.sin(x) * 20;
// 模拟QRS波群
if (i % 50 === 0) y = 60;
if (i % 50 === 1) y = -40;
this.dataPoints.push(y);
}
},
drawECG() {
const canvas = this.$refs.ecgCanvas;
const ctx = canvas.getContext('2d');
const { width, height } = this;
const animate = () => {
ctx.clearRect(0, 0, width, height);
// 绘制网格背景
ctx.strokeStyle = '#eee';
ctx.lineWidth = 1;
for (let i = 0; i < width; i += 20) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, height);
ctx.stroke();
}
for (let j = 0; j < height; j += 20) {
ctx.beginPath();
ctx.moveTo(0, j);
ctx.lineTo(width, j);
ctx.stroke();
}
// 绘制心电图
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.beginPath();
const offset = Date.now() / 100 % width;
for (let i = 0; i < width; i++) {
const dataIndex = Math.floor((i + offset) % this.dataPoints.length);
const y = height / 2 - this.dataPoints[dataIndex];
if (i === 0) ctx.moveTo(i, y);
else ctx.lineTo(i, y);
}
ctx.stroke();
this.animationId = requestAnimationFrame(animate);
};
animate();
},
},
};
</script>
<style>
.ecg-container {
background: #fff;
border: 1px solid #ddd;
}
</style>
使用 ECharts 实现
若需要更复杂的图表功能,可通过 ECharts 实现:
<template>
<div ref="ecgChart" style="width: 800px; height: 200px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chart = echarts.init(this.$refs.ecgChart);
const data = this.generateECGData();
const option = {
animation: false,
grid: { top: 10, right: 10, bottom: 10, left: 10 },
xAxis: { show: false, type: 'value' },
yAxis: { show: false, min: -1.5, max: 1.5 },
series: [{
type: 'line',
showSymbol: false,
data: data,
lineStyle: { color: 'red', width: 2 },
}]
};
chart.setOption(option);
// 动态更新数据
setInterval(() => {
data.shift();
data.push(this.generateECGPoint(data.length));
chart.setOption({ series: [{ data }] });
}, 100);
},
generateECGData() {
const data = [];
for (let i = 0; i < 200; i++) {
data.push(this.generateECGPoint(i));
}
return data;
},
generateECGPoint(i) {
// 模拟心电图波形
const x = i / 10;
if (i % 50 === 0) return 1.2;
if (i % 50 === 1) return -1.2;
return Math.sin(x) * 0.5;
}
}
};
</script>
关键点说明
- 数据生成:通过正弦波模拟基础心律,添加脉冲模拟 QRS 波群。
- 动态渲染:使用
requestAnimationFrame或定时器实现动画效果。 - 性能优化:对于长序列数据,可采用视窗渲染(仅显示可见区域数据)。
扩展功能
- 添加实时数据接口,连接真实 ECG 设备。
- 实现缩放、平移等交互功能。
- 添加心率计算等分析功能。






