How can I create a horizontal scrolling Chart.js line chart with a locked y axis?

后端 未结 7 1806
生来不讨喜
生来不讨喜 2020-11-29 00:39

I\'d like to create a line chart with Chart.Js but have the Y-Axis not move when I scroll.

I\'m assuming I can use a fixed width, and put i

7条回答
  •  醉梦人生
    2020-11-29 01:02

    All these answers are rather muddy and complex.. Heres what I went with for my project. I just call fitChart() whenever the dataset changes or the container size changes.

    HTML:

    CSS: (Set the width and height to whatever you want)

    div.chartWrapper {
        position: relative;
        overflow: auto;
        width: 100%;
    }
    
    div.chartContainer {
        position: relative;
        height: 300px;
    }
    

    JS:

    var xAxisLabelMinWidth = 15; // Replace this with whatever value you like
    var myChart = new Chart(document.getElementById('chart').getContext('2d'), {
        type: 'line',
        data: {},
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
    
    function fitChart(){
        var chartCanvas = document.getElementById('chart');
        var maxWidth = chartCanvas.parentElement.parentElement.clientWidth;
        var width = Math.max(mayChart.data.labels.length * xAxisLabelMinWidth, maxWidth);
    
        chartCanvas.parentElement.style.width = width +'px';
    }
    

提交回复
热议问题