Here is the code
<!DOCTYPE html>
<html>
<head>
<title>Bitcoin Kurs in Echtzeit</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
<style type="text/css">
#canvas {
max-width: 500px;
margin: 10px 0 10px 0;
padding: 10px;
border: 1px solid #d3d3d3;
}
</style>
</head>
<body>
<div id="canvas-container">
<canvas id="canvas" width="400" height="400"></canvas>
</div>
<script>
let endpoint = 'https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR';
let xValues = [];
let yValues = [];
//Abrufen der Daten in Echtzeit
let xhr = new XMLHttpRequest();
let chart = null;
xhr.open('GET', endpoint);
xhr.onload = () => {
if (xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
xValues.push(Date.now());
yValues.push(data.USD);
if (chart == null) {
chart = createChart(xValues, yValues);
} else {
chart.data.labels = xValues;
chart.data.datasets[0].data = yValues;
chart.update();
}
setTimeout(() => {
xhr.open('GET', endpoint);
xhr.send();
}, 1000);
} else {
console.error(xhr.statusText);
}
};
xhr.send();
//Erstellen des Charts
function createChart(xValues, yValues) {
let ctx = document.getElementById('canvas').getContext('2d');
return new Chart(ctx, {
type: 'line',
data: {
labels: xValues,
datasets: [{
label: 'Bitcoin Kurs in USD',
data: yValues,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
fill: false
}]
},
options: {
responsive: true
}
});
}
</script>
</body>
</html>
Leave a Reply