How I can prevent of labels overlapping on mobile screen Chart.js

試著忘記壹切 提交于 2019-12-22 07:02:49

问题


I am using this example jsfiddle on But When I use a small screen labels start to overlap like this

What I can do to prevent it ? I want to make it fully responsive. I tried to change length and other aspect ratios etc but no sucess.

    var ctx = $('#myChart');

ctx.height(500);

var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    maintainAspectRatio: false,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

回答1:


This can be prevented by changing the y-axis label­'s font size on-the-fly (dynamically). Though, in ChartJS there is no built-in method to do so, meaning no matter how you resize the chart, the font size will always be the same.

However, to get around this, you can use the following chart plugin, which will make the font size responsive ...

plugins: [{
   beforeDraw: function(c) {
      var chartHeight = c.chart.height;
      c.scales['y-axis-0'].options.ticks.fontSize = chartHeight * 6 / 100;
   }
}]

add this plugin followed by your chart options.

Here is a working example on jsFiddle




回答2:


You could add some CSS to stop the chart getting too small, forcing some users on mobile to scroll right: https://jsfiddle.net/panchroma/yybc26Lr/1/

The only change I made was add

.chart{
  min-width:300px;
}


来源:https://stackoverflow.com/questions/44540746/how-i-can-prevent-of-labels-overlapping-on-mobile-screen-chart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!