Functions
With chart.js you have 2 options.
- You can create mix chart types ( Example here ). This will allow you to add line charts to create your lines.
- You can create a plugin (see example below).
Option 2 will be the one I recommend, as it allows you more control over the appearance of the lines.
Correction
plugin demo
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 the code after the event occurs and resize 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);
L bahr
source share