Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
307 lines (266 loc) · 9.69 KB
/
Copy pathscript.js
File metadata and controls
307 lines (266 loc) · 9.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// script.js
// ECG Recorder Simulator
// Save as script.js and open index.html in a browser
const canvas = document.getElementById('ecgCanvas');
const ctx = canvas.getContext('2d');
// Controls
const bpmSlider = document.getElementById('bpm');
const bpmVal = document.getElementById('bpmVal');
const ampSlider = document.getElementById('amplitude');
const ampVal = document.getElementById('ampVal');
const speedSlider = document.getElementById('speed');
const speedVal = document.getElementById('speedVal');
const lpCheckbox = document.getElementById('lp');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const recordBtn = document.getElementById('recordBtn');
const downloadBtn = document.getElementById('downloadBtn');
const snapshotBtn = document.getElementById('snapshotBtn');
const samplesCountEl = document.getElementById('samplesCount');
bpmVal.textContent = bpmSlider.value;
ampVal.textContent = ampSlider.value;
speedVal.textContent = speedSlider.value;
bpmSlider.oninput = () => bpmVal.textContent = bpmSlider.value;
ampSlider.oninput = () => ampVal.textContent = ampSlider.value;
speedSlider.oninput = () => speedVal.textContent = speedSlider.value;
// Canvas sizing for high-DPI
function resizeCanvas() {
const ratio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * ratio;
canvas.height = canvas.clientHeight * ratio;
ctx.setTransform(ratio,0,0,ratio,0,0);
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// Drawing grid
function drawGrid() {
const w = canvas.clientWidth;
const h = canvas.clientHeight;
ctx.clearRect(0,0,w,h);
// background
ctx.fillStyle = '#041026';
ctx.fillRect(0,0,w,h);
// small grid
const step = 10;
ctx.strokeStyle = 'rgba(0,200,160,0.06)';
ctx.lineWidth = 1;
for(let x=0;x<w;x+=step){ ctx.beginPath(); ctx.moveTo(x,0); ctx.lineTo(x,h); ctx.stroke(); }
for(let y=0;y<h;y+=step){ ctx.beginPath(); ctx.moveTo(0,y); ctx.lineTo(w,y); ctx.stroke(); }
// thicker grid every 5
ctx.strokeStyle = 'rgba(0,200,160,0.12)';
ctx.lineWidth = 1.4;
for(let x=0;x<w;x+=step*5){ ctx.beginPath(); ctx.moveTo(x,0); ctx.lineTo(x,h); ctx.stroke(); }
for(let y=0;y<h;y+=step*5){ ctx.beginPath(); ctx.moveTo(0,y); ctx.lineTo(w,y); ctx.stroke(); }
}
drawGrid();
// ECG signal generator (template beat + jitter)
function makeBeatTemplate(length, height) {
// create a single heartbeat template (array of samples)
// We'll produce a QRS-like spike using gaussian + low hump for P/T waves
const arr = new Float32Array(length);
const center = Math.floor(length * 0.35);
const qrsWidth = Math.max(1, Math.floor(length * 0.02));
for(let i=0;i<length;i++){
// baseline small noise
let v = 0.01 * Math.sin(i*0.03);
// P-wave (small Gaussian)
v += 0.08 * Math.exp(-Math.pow((i - Math.floor(length*0.15)),2)/(2*(length*0.03)**2));
// QRS: sharp spike
v += 1.0 * Math.exp(-Math.pow((i-center),2)/(2*(qrsWidth)**2));
// T-wave: broader hump after QRS
v += 0.3 * Math.exp(-Math.pow((i - Math.floor(length*0.6)),2)/(2*(length*0.06)**2));
arr[i] = v * height;
}
return arr;
}
// Basic lowpass smoothing filter
function simpleLowpass(prev, cur, alpha=0.12) {
return prev + (cur - prev) * alpha;
}
// State
let running = false;
let recording = false;
let recordBuffer = []; // {t, sample}
let samplesRecorded = 0;
let sampleRate = parseInt(speedSlider.value); // samples per second
let bpm = parseInt(bpmSlider.value);
let amplitude = parseFloat(ampSlider.value);
let lastDrawX = 0;
// streaming buffer for display
const displayBuffer = []; // small circular buffer of recent samples
const maxDisplaySamples = 2000;
// beat template
let beatTemplate = makeBeatTemplate(300, 1.0);
// animation timing
let lastTime = null;
let carry = 0; // time carry for sampling
// drawing parameters
const margin = 12;
const gridColor = '#003b2e';
const lineColor = '#00ffb0';
function updateSettingsFromUI(){
sampleRate = parseInt(speedSlider.value);
bpm = parseInt(bpmSlider.value);
amplitude = parseFloat(ampSlider.value);
// regenerate template length relative to BPM and sampleRate
const beatIntervalSec = 60 / bpm;
const beatSamples = Math.max(80, Math.floor(beatIntervalSec * sampleRate));
beatTemplate = makeBeatTemplate(beatSamples, 1.0);
}
// function to generate next sample based on time and beat position
let beatPhase = 0; // index inside current beat
let beatIntervalSamples = Math.max(1, Math.floor((60 / bpm) * sampleRate));
function nextSample() {
// ensure beat length syncs with bpm and sampleRate
beatIntervalSamples = Math.max(1, Math.floor((60 / bpm) * sampleRate));
// sample index inside beat template (wrap)
const idx = Math.floor((beatPhase / beatIntervalSamples) * beatTemplate.length) % beatTemplate.length;
// base sample from template
let s = beatTemplate[idx] * amplitude;
// add small baseline wander / noise
s += 0.02 * Math.sin(beatPhase * 0.02) + (Math.random() - 0.5) * 0.01;
// advance
beatPhase = (beatPhase + 1) % beatIntervalSamples;
return s;
}
// drawing routine: sliding plot
function drawWave() {
const w = canvas.clientWidth;
const h = canvas.clientHeight;
drawGrid();
// axes center
const midY = h / 2;
// draw waveform
ctx.lineWidth = 2;
ctx.strokeStyle = lineColor;
ctx.beginPath();
const visible = displayBuffer.slice(-maxDisplaySamples);
const len = visible.length;
const pxPerSample = Math.max(0.25, w / Math.max(200, len));
// draw from left to right
let x = margin;
for (let i = 0; i < len; i++) {
const val = visible[i];
// scale
const y = midY - val * (h * 0.3); // vertical scale
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
x += pxPerSample;
}
ctx.stroke();
// draw center baseline
ctx.strokeStyle = 'rgba(0,255,176,0.12)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, midY);
ctx.lineTo(w, midY);
ctx.stroke();
}
// main loop - uses requestAnimationFrame and internal sampling to allow different sample rates
function loop(timestamp) {
if (!lastTime) lastTime = timestamp;
const dt = (timestamp - lastTime) / 1000.0; // seconds
lastTime = timestamp;
if (running) {
// update settings live
updateSettingsFromUI();
// compute how many samples to generate this frame
const samplesToGenerateFloat = sampleRate * dt + carry;
const samplesToGenerate = Math.floor(samplesToGenerateFloat);
carry = samplesToGenerateFloat - samplesToGenerate;
for (let i = 0; i < samplesToGenerate; i++) {
let s = nextSample();
// optional smoothing (lowpass)
if (lpCheckbox.checked && displayBuffer.length>0) {
const prev = displayBuffer[displayBuffer.length - 1];
s = simpleLowpass(prev, s, 0.14);
}
displayBuffer.push(s);
if (displayBuffer.length > maxDisplaySamples) displayBuffer.shift();
// recording
if (recording) {
const now = Date.now();
recordBuffer.push({t: now, sample: s});
samplesRecorded++;
}
}
// update UI count
samplesCountEl.textContent = samplesRecorded;
}
drawWave();
rafId = requestAnimationFrame(loop);
}
let rafId = requestAnimationFrame(loop);
// control handlers
startBtn.addEventListener('click', () => {
if (!running) {
running = true;
lastTime = null;
startBtn.disabled = true;
stopBtn.disabled = false;
}
});
stopBtn.addEventListener('click', () => {
running = false;
startBtn.disabled = false;
stopBtn.disabled = true;
});
recordBtn.addEventListener('click', () => {
if (!recording) {
recording = true;
recordBuffer = [];
samplesRecorded = 0;
recordBtn.textContent = 'Stop Recording';
downloadBtn.disabled = true;
} else {
recording = false;
recordBtn.textContent = 'Start Recording';
downloadBtn.disabled = recordBuffer.length === 0;
}
});
downloadBtn.addEventListener('click', () => {
if (recordBuffer.length === 0) return;
// create CSV: time (ms since start), sample
const startT = recordBuffer[0].t;
let csv = 'time_ms,sample\n';
for (const r of recordBuffer) {
csv += `${r.t - startT},${r.sample}\n`;
}
const blob = new Blob([csv], {type: 'text/csv'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `ecg_record_${new Date().toISOString().replace(/[:.]/g,'-')}.csv`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
});
snapshotBtn.addEventListener('click', () => {
// save canvas as PNG
// for nicer PNG, draw on a temporary canvas at native pixel size
const link = document.createElement('a');
link.download = `ecg_snapshot_${new Date().toISOString().replace(/[:.]/g,'-')}.png`;
// toDataURL on visible canvas:
// Because we used transform for device pixel ratio, toDataURL will be fine with current canvas size
link.href = canvas.toDataURL('image/png');
document.body.appendChild(link);
link.click();
link.remove();
});
// live UI update to ensure settings update while running
[bpmSlider, ampSlider, speedSlider, lpCheckbox].forEach(el => {
el.addEventListener('input', () => {
// when bpm or speed changes, reset some phasing so beat timing stays consistent
updateSettingsFromUI();
// don't reset stored recorded data
});
});
// keyboard shortcut: space toggles run/stop
window.addEventListener('keydown', (e) => {
if (e.code === 'Space') {
e.preventDefault();
if (running) stopBtn.click();
else startBtn.click();
}
});