简体   繁体   中英

Chartjs v3 tooltip label not showing tooltip label color on custom calbacks

I've created line chart using chartjs v3. I've used custom tooltip callback function to show tooltip data on hidden dataset/series but I don't know why label color squar shows only on one series. Anybody know why it happens like this? 工具提示标签

 [https://codepen.io/eidsza/pen/mdWoqOJ][2]

Its because your placement of the tooltip options is wrong.And the label callback runs for every entry, chart.js places the color in front of it automatically so you shouldnt return an array but just the single transformed entry for that line, final part dont use the v3 beta, use the latest version.

Example:

 var ctx = document.getElementById("chart").getContext("2d"); var chart = new Chart(ctx, { type: "bar", data: { labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], datasets: [{ key: 1, label: 'series a', backgroundColor: "rgb(255, 99, 132, 0.5)", borderColor: "rgb(255, 99, 132)", borderWidth: 1, lineTension: 0.3, data: [10, 7, 9, 5, 8, 3, 4, 2, 1, 1] }, { key: 2, label: 'series b', backgroundColor: "rgb(30, 105, 122, 0.5)", borderColor: "rgb(30, 105, 122)", borderWidth: 1, lineTension: 0.3, data: [1, 9, 4, 9, 3, 2, 1, 8, 6, 5] }, ] }, options: { interaction: { intersect: false, mode: 'index', }, plugins: { tooltip: { callbacks: { // No callback needed since it seems you want the default behaviour // label: (item) => { // // console.log(item.chart) // // if (item.datasetIndex == item.chart.data.datasets.length - 1) { // return item.chart.data.datasets.map(ds => ds.label + ': ' + ds.data[item.dataIndex]); // // } // // return null; // } } } } } });
 .chart { max-width: 600px; max-height: 400px; } canvas { -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; }
 <div class="chart"> <canvas id="chart"></canvas> </div> <div class="chart"> <canvas id="chart2"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@3.3.2/dist/chart.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM