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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How can I create a horizontal scrolling Chart.js line chart with a locked y axis? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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 it in a container div with overflow:auto, but then The Y-axis info is attached to the canvas and scrolls along.

I don’t see a parameter or option for this in the docs. Any ideas?

Thank you

Answer

Scrollable Chart

You’re pretty much on the right track. If you add another wrapper and the y axis you are done.


Preview

enter image description here


CSS

.chartWrapper {
    position: relative;
}

.chartWrapper > canvas {
    position: absolute;
    left: 0;
    top: 0;
    pointer-events:none;
}

.chartAreaWrapper {
    width: 600px;
    overflow-x: scroll;
}

HTML

<div class="chartWrapper">
    <div class="chartAreaWrapper">
        <canvas id="myChart" height="300" width="1200"></canvas>
    </div>
    <canvas id="myChartAxis" height="300" width="0"></canvas>
</div>

Script

...

new Chart(ctx).Line(data, {
    onAnimationComplete: function () {
        var sourceCanvas = this.chart.ctx.canvas;
        // the -5 is so that we don't copy the edges of the line
        var copyWidth = this.scale.xScalePaddingLeft - 5;
        // the +5 is so that the bottommost y axis label is not clipped off
        // we could factor this in using measureText if we wanted to be generic
        var copyHeight = this.scale.endPoint + 5;
        var targetCtx = document.getElementById("myChartAxis").getContext("2d");
        targetCtx.canvas.width = copyWidth;
        targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth, copyHeight, 0, 0, copyWidth, copyHeight);
    }
});

Fiddle – http://jsfiddle.net/mbhavfwm/

We are here to answer your question about How can I create a horizontal scrolling Chart.js line chart with a locked y axis? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji