canvas绘制心电图
html
<div class="information_bottom_right" id="grids">
<img src="@/assets/img/grids.png" alt="">
<canvas :id="'ecg'+id" :class="'canvas'+id" class="canvas ecgcanvas"></canvas>
</div>
js
变量leadData是心电数据,类型是数组,举例:[2,3,5,5…],可以用随机数试一下
data(){
return{
ecgh: '',
trimer: null,
number: 0,
carouselWidth:0,
warningdata: {},
falg: true,
hr:'',
distance: '',
bind_time: '',
event_name: '',
event_level: '',
myChart:null,
leadData: [],
index: 0,
num: 0,
sampleRate: 125,//采样率
multiple1:0,
time: 80,
count: 10,//每次更新10个点
x: 0,//心电图x的值
n: 0,//画心电图的位置
leadDataIndex: 0,//心电数据下标
num: 0,//假数据画心电图的位置
canvasw: 0,
canvash: 0,
clearx: 12,//橡皮擦,第二波数据时擦掉的长度
length:0,
clientW:0,
hrIndex:0
}
},
mounted(){
let canvas = document.getElementsByClassName('canvas'+that.id)
//获取devicePixelRatio
that.canvasw = document.querySelector('.information_bottom_right').clientWidth
that.canvash = document.querySelector('.information_bottom_right').clientHeight
canvas.style.width = that.canvasw + "px"
canvas.style.height = that.canvash + "px"
that.setcanvas(canvas)
},
setcanvas(canvas){//开启定时器,初始化画布
let dateNow = new Date()
let that = this
localStorage.setItem('starTime',new Date().valueOf())
var dpr = window.devicePixelRatio || 1;
canvas.width = this.canvasw *dpr
canvas.height = this.canvash *dpr
const ctx = canvas.getContext('2d')
//注意如下代码
ctx.scale(dpr, dpr)
if (!ctx) return
ctx.beginPath()
ctx.strokeStyle = '#fff'
ctx.lineWidth = 1
ctx.lineJoin = "round"
ctx.moveTo(0, this.canvash/2)
if(this.warningdata.leadData){
this.leadData = this.warningdata.leadData
}
this.trimer = setInterval(function () {
let starTime = localStorage.getItem('starTime'+that.id)
let endTime = new Date().valueOf()
if(endTime - parseInt(starTime)>80){
that.time = 80 - (endTime - parseInt(starTime))
}else if(endTime - parseInt(starTime)<80){
that.time = 80 + (endTime - parseInt(starTime))
}
if (that.leadData && that.leadData.length >= (2*750)) {
that.DrawEcg(ctx)
}
localStorage.setItem('starTime'+that.id,new Date().valueOf())
}, this.time)
},
DrawEcg(ctx){ //实时心电图
let that = this
if(that.n >= (that.sampleRate * that.second)){
ctx.beginPath()
that.count = 11
that.x = 0
that.n=0
that.num = 0
}
for(let i = 0;i<that.count;i++){
if(i==0){
ctx.clearRect(that.x,0,that.clearx,(that.canvash))
}
if(i<10){
that.n++
that.num++
that.hrIndex++
that.x = that.n*(that.canvasw/(that.sampleRate * that.second))
that.leadDataIndex++
if(that.leadDataIndex>=(5*750) || that.leadDataIndex>that.leadData.length){
that.leadDataIndex = 0
}
if(that.hrIndex%125==0){
that.hr = that.hrList[that.hrIndex/125]
if(that.hrIndex/125 == 5){
that.hrIndex=0
}
}
if(that.leadData[that.leadDataIndex]){
ctx.lineTo(that.x, (that.leadData[that.leadDataIndex]) + (this.canvash/2))
}else{
ctx.lineTo(that.x, (this.canvash/2))
}
}else{
ctx.clearRect(that.x,0,that.clearx,(that.canvash))
}
}
ctx.stroke()
},