自己学习(捣腾)的时间到了,今天弄个虚假的心电图
效果图:
这里数据都是随机的,波形很不优雅 =.=
贴一下代码:
<!DOCTYPE html>
<html lang="cms-Hans-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>心电图</title>
</head>
<body>
<div class="box">
<canvas id="myCanvas"></canvas>
</div>
</body>
<script>
var myCanvas = document.getElementById("myCanvas")
// 画布
myCanvas.width = 800
myCanvas.height = 400
var ctx = myCanvas.getContext('2d')
ctx.fillStyle = "#2F4F4F";
ctx.fillRect(0, 0, 800, 400);
var x = 0
var y = myCanvas.height / 2
var x2 = 0
var y2 = myCanvas.height / 2
function setLine() {
ctx.strokeStyle = "#7CFC00"
ctx.beginPath(); //新建一条path
ctx.moveTo(x, y); //把画笔移动到指定的坐标
ctx.lineTo(x2, y2); //绘制一条从当前位置到指定坐标(200, 50)的直线.
//闭合路径。会拉一条从当前点到path起始点的直线。如果当前点与起始点重合,则什么都不做
ctx.closePath();
ctx.stroke(); //绘制路径。
}
//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
switch (arguments.length) {
case 1:
return parseInt(Math.random() * minNum + 1, 10);
break;
case 2:
return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
break;
default:
return 0;
break;
}
}
var timer = setInterval(() => {
x = x2
x2 = x2 + 5
y = y2
y2 = this.randomNum(100, 300)
if (x > 800) {
console.log("停")
// clearInterval(timer)
this.oneAgain()
return
}
this.setLine()
}, 50);
// 画到屏幕清空重新绘制
function oneAgain() {
myCanvas.width = 800
myCanvas.height = 400
ctx = myCanvas.getContext('2d')
ctx.fillStyle = "#2F4F4F";
ctx.fillRect(0, 0, 800, 400);
x = 0
y = myCanvas.height / 2
x2 = 0
y2 = myCanvas.height / 2
}
// 退出页面刷新页面销毁定时器
window.onbeforeunload = function () {
clearInterval(timer)
}
</script>
</html>