简体   繁体   中英

Chart.js - How to Add Text in the label of the Chart with JavaScript?

i don't know how to add text on in the label of the Chart JavaScript. My chart use on PC and Tablet.

now chart

https://i.stack.imgur.com/9BanV.png

But I need to label the responsive zones, something like this:

https://i.stack.imgur.com/uhIp9.png

https://i.stack.imgur.com/WyDnW.png

<canvas id="myChart" width="500" height="400"></canvas>

==== My code ( in 1 label data 12 month - 10 year = 1 x bar)

var color = Chart.helpers.color;
var barChartData = {

    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    datasets: [{
        type: 'bar',
        label: '<?php echo $year9+543; ?>',
        fill: false,
        borderColor: "rgba(235,189,139,1)",
        data: <? php echo $data_target9_month; ?>
    }, ... Array data ...

edit graph

window.onload = function () {
    var ctx = document.getElementById('canvas').getContext('2d');
    window.myBar = new Chart(ctx, {
        type: 'bar',
        data: barChartData,
        options: {
            elements: {
                line: {
                    tension: 0
                }
            },
            tooltips: {
                mode: 'index',

                intersect: false,
                callbacks: {
                    label: function (tooltipItem, data) {
                        var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                        if (parseInt(value) >= 1000) {
                            return data.datasets[tooltipItem.datasetIndex].label + " : " + '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                        }
                        if (parseInt(value) == 0) {
                            return data.datasets[tooltipItem.datasetIndex].label + " : " + 'ไม่มีข้อมูล';
                        }
                        else {
                            return data.datasets[tooltipItem.datasetIndex].label + " : " + '$' + value;
                        }

                    }
                } // end callbacks:
            }
        }
    })

thanks.

That is for sure achievable using Chart.JS methods but the best and easiest way to do it is to simply overlap the texts you want to add using position: absolute; on each text box.

Take a look at this JSFiddle: https://jsfiddle.net/gxjw5hLb/

Of course, you will need to calculate and replace the values for each "X",

<td><span>X=1000</span></td>
<td><span>X=2500</span></td>
<td><span>X=3000</span></td>

Also the boxes would need some additional CSS styling.

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