1

There's a nice new release of Chart.js out, which appears to be a little more intuitive to use. But I'm trying some code designed with V1 and it's not working, but getting this deep into it, is a little beyond me - the code I'm trying to use is the last post here - http://yuluer.com/page/dbajceij-chart-js-draw-horizontal-line.shtml

My code for the line graph is as follows:

$.ajax({
        url : "getData.asp",
        type: "POST",
        data : {
                database: dataBase,
                sn: Options,
                opts: opt,
                dateRange: dateRange
            },
        dataType:"json",
         success: function(result){
            var Result = (result)
            Array.prototype.mapProperty = function(property) {
              return this.map(function (obj) {
               return obj[property];
              });

             };
            var ctx = document.getElementById("chart");
            var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                    labels: result.mapProperty('sn'),
                    datasets: [{
                        label: opt,
                        data: result.mapProperty('data')
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: false
                            }
                        }]
                    }
                }
            }); 
})

Has anyone managed to get custom dynamic straight lines on V2?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Hyperjase
  • 127
  • 2
  • 21

1 Answers1

1

See Chart.js 2.0 - vertical lines

The Sample mentioned there draws a vertical line at xaxis index configured with the data value "lineAtIndex". To draw a horizontal line, you could adapt the sample the following way:

var originalLineDraw = Chart.controllers.line.prototype.draw;

Chart.helpers.extend(Chart.controllers.line.prototype, {
    draw: function() {

        originalLineDraw.apply(this, arguments);

        var chart = this.chart;
        var ctx = chart.chart.ctx;

        var lineAtValue = chart.config.data.lineAtValue;
        if (lineAtValue) {

            var xaxis = chart.scales['x-axis-0'];
            var yaxis = chart.scales['y-axis-0'];

            ctx.save();
            ctx.beginPath();
            ctx.moveTo(xaxis.left, yaxis.getPixelForValue(lineAtValue));
            ctx.strokeStyle = '#ff0000';
            ctx.lineTo(xaxis.right, yaxis.getPixelForValue(lineAtValue));
            ctx.stroke();
            ctx.restore();

        }
    }
});

The configuration would then be:

var chart = new Chart(ctx, {
    type: 'your-type',
    data: {
        labels: [your-labels],
        datasets: [...],
        lineAtValue: 20000
    },
    options: defaultOptions
});
Community
  • 1
  • 1
jjarolim
  • 121
  • 4