Created
January 26, 2023 08:08
-
-
Save x8BitRain/384d2e7f395d486d1e116e2552e3ea5b to your computer and use it in GitHub Desktop.
ChartJS Data Streaming in Vue 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<canvas ref="chartRef" class="main-canvas"></canvas> | |
</template> | |
<script setup lang="ts"> | |
import { ref, onMounted } from 'vue' | |
import {transparentize, rand, CHART_COLORS} from './utils/utils.js' | |
import ChartStreaming from 'chartjs-plugin-streaming'; | |
import { | |
Chart as ChartJS, | |
CategoryScale, | |
LinearScale, | |
PointElement, | |
LineElement, | |
Title, | |
Tooltip, | |
Legend, | |
} from "chart.js"; | |
const chartRef = ref(null) | |
ChartJS.register( | |
CategoryScale, | |
LinearScale, | |
PointElement, | |
LineElement, | |
Title, | |
Tooltip, | |
Legend, | |
ChartStreaming | |
); | |
const data = { | |
datasets: [ | |
{ | |
label: 'Dataset 1 (Line)', | |
backgroundColor: transparentize(CHART_COLORS.red, 0.5), | |
borderColor: CHART_COLORS.red, | |
cubicInterpolationMode: 'monotone', | |
data: [] | |
}, | |
{ | |
type: 'bar', | |
label: 'Dataset 2 (Bars)', | |
backgroundColor: transparentize(CHART_COLORS.blue, 0.5), | |
borderColor: CHART_COLORS.blue, | |
borderWidth: 1, | |
data: [] | |
} | |
] | |
}; | |
const generateData = chart => { | |
// Mock incoming data from an endpoint/websocket | |
const now = Date.now(); | |
chart.data.datasets.forEach(dataset => { | |
dataset.data.push({ | |
x: now, | |
y: rand(-100, 100) | |
}); | |
}); | |
}; | |
const config = { | |
type: 'line', | |
data: data, | |
options: { | |
scales: { | |
x: { | |
type: 'realtime', | |
realtime: { | |
duration: 20000, | |
refresh: 1000, | |
delay: 2000, | |
onRefresh: generateData | |
} | |
}, | |
y: { | |
title: { | |
display: true, | |
text: 'Value' | |
} | |
} | |
}, | |
interaction: { | |
mode: 'nearest', | |
intersect: false | |
} | |
} | |
}; | |
onMounted(() => { | |
// Get the canvas context after rendering and initialize the chart on mount. | |
const ctx = chartRef.value.getContext('2d') | |
const chart = new ChartJS(ctx, config) | |
}) | |
</script> | |
<style> | |
#app { | |
font-family: Avenir, Helvetica, Arial, sans-serif; | |
-webkit-font-smoothing: antialiased; | |
-moz-osx-font-smoothing: grayscale; | |
} | |
.main-canvas { | |
width: 800px; | |
height: 600px; | |
margin: 0 auto; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment