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

后端 未结 7 1810
生来不讨喜
生来不讨喜 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

    Scrollable Chart

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


    Preview


    CSS

    .chartWrapper {
        position: relative;
    }
    
    .chartWrapper > canvas {
        position: absolute;
        left: 0;
        top: 0;
        pointer-events:none;
    }
    
    .chartAreaWrapper {
        width: 600px;
        overflow-x: scroll;
    }
    

    HTML

    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/

提交回复
热议问题