-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
74 lines (66 loc) · 2.44 KB
/
app.js
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
var canvas = document.querySelector('canvas');
var statusText = document.querySelector('#statusText');
statusText.addEventListener('click', function() {
statusText.textContent = 'Breathe...';
heartRates = [];
heartRateSensor.connect()
.then(() => heartRateSensor.startNotificationsHeartRateMeasurement().then(handleHeartRateMeasurement))
.catch(error => {
statusText.textContent = error;
});
});
function handleHeartRateMeasurement(heartRateMeasurement) {
heartRateMeasurement.addEventListener('characteristicvaluechanged', event => {
var heartRateMeasurement = heartRateSensor.parseHeartRate(event.target.value);
statusText.innerHTML = heartRateMeasurement.heartRate + ' ❤';
heartRates.push(heartRateMeasurement.heartRate);
drawWaves();
});
}
var heartRates = [];
var mode = 'bar';
canvas.addEventListener('click', event => {
mode = mode === 'bar' ? 'line' : 'bar';
drawWaves();
});
function drawWaves() {
requestAnimationFrame(() => {
canvas.width = parseInt(getComputedStyle(canvas).width.slice(0, -2)) * devicePixelRatio;
canvas.height = parseInt(getComputedStyle(canvas).height.slice(0, -2)) * devicePixelRatio;
var context = canvas.getContext('2d');
var margin = 2;
var max = Math.max(0, Math.round(canvas.width / 11));
var offset = Math.max(0, heartRates.length - max);
context.clearRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = '#00796B';
if (mode === 'bar') {
for (var i = 0; i < Math.max(heartRates.length, max); i++) {
var barHeight = Math.round(heartRates[i + offset ] * canvas.height / 200);
context.rect(11 * i + margin, canvas.height - barHeight, margin, Math.max(0, barHeight - margin));
context.stroke();
}
} else if (mode === 'line') {
context.beginPath();
context.lineWidth = 6;
context.lineJoin = 'round';
context.shadowBlur = '1';
context.shadowColor = '#333';
context.shadowOffsetY = '1';
for (var i = 0; i < Math.max(heartRates.length, max); i++) {
var lineHeight = Math.round(heartRates[i + offset ] * canvas.height / 200);
if (i === 0) {
context.moveTo(11 * i, canvas.height - lineHeight);
} else {
context.lineTo(11 * i, canvas.height - lineHeight);
}
context.stroke();
}
}
});
}
window.onresize = drawWaves;
document.addEventListener("visibilitychange", () => {
if (!document.hidden) {
drawWaves();
}
});