From: Evert Timberg Date: Mon, 23 Nov 2015 03:31:08 +0000 (-0500) Subject: Initial toggling of datasets from the legend. X-Git-Tag: 2.0.0-beta2~25^2~22 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=60c1609ba9f41f29b3e926d776dc0a78a097930a;p=thirdparty%2FChart.js.git Initial toggling of datasets from the legend. Still need to do: - clicking on text in legend - toggling style of legend based on dataset style - figure out if we need an --- diff --git a/src/core/core.controller.js b/src/core/core.controller.js index 2b78ab233..f05269c76 100644 --- a/src/core/core.controller.js +++ b/src/core/core.controller.js @@ -448,6 +448,10 @@ if (this.options.onClick) { this.options.onClick.call(this, e, this.active); } + + if (this.legend && this.legend.handleEvent) { + this.legend.handleEvent(e); + } } var dataset; diff --git a/src/core/core.legend.js b/src/core/core.legend.js index b8bf96734..d6abcafad 100644 --- a/src/core/core.legend.js +++ b/src/core/core.legend.js @@ -47,6 +47,9 @@ initialize: function(config) { helpers.extend(this, config); this.options = helpers.configMerge(Chart.defaults.legend, config.options); + + // Contains hit boxes for each dataset (in dataset order) + this.legendHitBoxes = []; }, // These methods are ordered by lifecyle. Utilities then follow. @@ -196,6 +199,9 @@ // Actualy draw the legend on the canvas draw: function() { + // Reset hit boxes + this.legendHitBoxes = []; + if (this.options.display) { console.log(this.labelWidths); @@ -254,6 +260,13 @@ ctx.fillRect(cursor.x, cursor.y, this.options.labels.boxWidth, this.options.labels.fontSize); ctx.restore(); + // Store the hitbox + this.legendHitBoxes[i] = { + left: cursor.x, + top: cursor.y, + right: cursor.x + this.options.labels.boxWidth, + bottom: cursor.y + this.options.labels.fontSize, + }; ctx.fillText(label, this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + cursor.x, cursor.y); cursor.x += width + (this.options.labels.padding); @@ -303,6 +316,30 @@ } } + }, + + // Handle an event + handleEvent: function(e) { + var position = helpers.getRelativePosition(e, this.chart.chart); + + if (position.x >= this.left && position.x <= this.right && position.y >= this.top && position.y <= this.bottom) { + // Legend is active + if (this.options.onClick) { + this.options.onClick.call(this, e); + } else { + // See if we are touching one of the dataset boxes + for (var i = 0; i < this.legendHitBoxes.length; ++i) { + var hitBox = this.legendHitBoxes[i]; + if (position.x >= hitBox.left && position.x <= hitBox.right && position.y >= hitBox.top && position.y <= hitBox.bottom) { + this.chart.data.datasets[i].hidden = !this.chart.data.datasets[i].hidden; + + // We hid a dataset ... rerender the chart + this.chart.render(); + break; + } + } + } + } } });