score:25

Accepted answer

options

with chart.js you have 2 options.

  1. you could create a mix chart types (example here). this would allow you to add a line charts to create your lines.
  2. you could create a plugin (see example below).

option 2 would be the one i recommend as it allows you to have more control over the appearance of the lines.

the fix

demo of the plugin

chart.js now supports plugins. this allows you to add any features you want to your charts!

to create a plugin you will need to run code after an event has occurred and modify the chart/canvas as needed. the following code should give you a good starting point:

var horizonallineplugin = {
  afterdraw: function(chartinstance) {
    var yvalue;
    var yscale = chartinstance.scales["y-axis-0"];
    var canvas = chartinstance.chart;
    var ctx = canvas.ctx;
    var index;
    var line;
    var style;

    if (chartinstance.options.horizontalline) {
      for (index = 0; index < chartinstance.options.horizontalline.length; index++) {
        line = chartinstance.options.horizontalline[index];

        if (!line.style) {
          style = "rgba(169,169,169, .6)";
        } else {
          style = line.style;
        }

        if (line.y) {
          yvalue = yscale.getpixelforvalue(line.y);
        } else {
          yvalue = 0;
        }

        ctx.linewidth = 3;

        if (yvalue) {
          ctx.beginpath();
          ctx.moveto(0, yvalue);
          ctx.lineto(canvas.width, yvalue);
          ctx.strokestyle = style;
          ctx.stroke();
        }

        if (line.text) {
          ctx.fillstyle = style;
          ctx.filltext(line.text, 0, yvalue + ctx.linewidth);
        }
      }
      return;
    }
  }
};
chart.pluginservice.register(horizonallineplugin);

Related Query

More Query from same tag