Created
May 15, 2020 08:17
-
-
Save Juszczak/98445a8cf3cc5295715a3b23999f1008 to your computer and use it in GitHub Desktop.
Chart.js Custom Tooltip
This file contains hidden or 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
<div id="weather-wrapper"> | |
<canvas id="weather-canvas"></canvas> | |
<canvas id="canvas"></canvas> | |
</div> |
This file contains hidden or 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
#weather-wrapper { | |
position: relative; | |
} | |
#weather-icon-tooltip { | |
position: absolute; | |
background-color: rgba(0, 0, 0, 0.4); | |
padding: 6px; | |
color: #f5f5f5; | |
} |
This file contains hidden or 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
options: { | |
tooltips: { | |
enabled: false, | |
custom: function (data) { | |
const item = data.dataPoints; // pobranie tablicy elementów związanych z danym punktem | |
// jeśli modele danych istnieją (najechanie myszką) | |
if (item) { | |
// mamy tylko jeden dataset, więc bierzemy pierwszy element dla danego punktu | |
const weatherPoint = item[0]; | |
// w zmiennej weatherPoint mamy dostęp do wartości czy też indexu danego punktu | |
console.log(weatherPoint); | |
// tutaj logiga na podstawie której wybieramy ikonkę na podstawie danych z weatherPoint | |
// dla przykładu losowa ikona, musisz tutaj to obsłużyć po swojemu na podstawie danych z weatherPoint | |
const randomIconKey = ['01d', '02d', '03d', '04d', '09d', '10d', '11d'][Math.floor(Math.random() * 6)]; | |
const icon = getIcon(randomIconKey); | |
// tworzymy customowy tooltip i ustawiamy wszystkie niezbędne parametry | |
const tooltip = document.createElement('div'); | |
tooltip.id = 'weather-icon-tooltip'; | |
tooltip.style.top = `${data.caretY + 40}px`; | |
tooltip.style.left = `${data.caretX + 40}px`; | |
tooltip.innerHTML = `<i class="fas ${icon}"></i> <span>${weatherPoint.yLabel}</span>`; | |
document.getElementById('weather').appendChild(tooltip); | |
} else { | |
// brak modelu danych, kasujemy element tooltipa | |
const existing = document.getElementById('weather-icon-tooltip'); | |
document.getElementById('weather').removeChild(existing); | |
} | |
}, | |
}, | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment