From 609e9eba7197a5ed9bf6b1a041226fa8acde1670 Mon Sep 17 00:00:00 2001 From: Matthew Hailwood Date: Thu, 21 Nov 2019 14:22:56 +1300 Subject: [PATCH] Fix trend line writing over axis. Fixes #21 --- src/chartjs-plugin-trendline.js | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/chartjs-plugin-trendline.js b/src/chartjs-plugin-trendline.js index a009c53..43460c4 100644 --- a/src/chartjs-plugin-trendline.js +++ b/src/chartjs-plugin-trendline.js @@ -58,6 +58,27 @@ function addFitter(datasetMeta, ctx, dataset, xScale, yScale) { var y1 = yScale.getPixelForValue(fitter.f(fitter.minx)); var y2 = yScale.getPixelForValue(fitter.f(fitter.maxx)); if ( !xy ) { x1 = startPos; x2 = endPos; } + + const drawBottom = datasetMeta.controller.chart.chartArea.bottom; + const chartWidth = datasetMeta.controller.chart.width; + + if(y1 > drawBottom) { // Left side is below zero + const diff = y1 - drawBottom; + const lineHeight = y1 - y2; + const overlapPercentage = diff / lineHeight; + const addition = chartWidth * overlapPercentage; + + y1 = drawBottom; + x1 = (x1 + addition); + } else if(y2 > drawBottom) { // right side is below zero + const diff = y2 - drawBottom; + const lineHeight = y2 - y1; + const overlapPercentage = diff / lineHeight; + const subtraction = chartWidth - (chartWidth * overlapPercentage); + + y2 = drawBottom; + x2 = chartWidth - (x2 - subtraction); + } ctx.lineWidth = lineWidth; if (lineStyle === "dotted") { ctx.setLineDash([2, 3]); } @@ -96,4 +117,4 @@ LineFitter.prototype = { var scale = (this.count * this.sumXY - this.sumX * this.sumY) / det; return offset + x * scale; } -}; \ No newline at end of file +};