From 5fae4dd3050fbd51da13ec1f5433d7f487758763 Mon Sep 17 00:00:00 2001 From: zachpanz88 Date: Sat, 4 Jun 2016 14:14:16 -0400 Subject: [PATCH] Change this -> me in source files This change allows for smaller minified code in the final version, resulting in a smaller file size. Some files had previously used _this, but that has been changed to me to keep consistency throughout the project. --- docs/01-Chart-Configuration.md | 1 + docs/09-Advanced.md | 5 + src/controllers/controller.bar.js | 177 ++++++------- src/controllers/controller.doughnut.js | 30 +-- src/controllers/controller.line.js | 2 +- src/controllers/controller.polarArea.js | 28 +-- src/controllers/controller.radar.js | 30 +-- src/core/core.animation.js | 56 +++-- src/core/core.controller.js | 235 ++++++++++-------- src/core/core.datasetController.js | 18 +- src/core/core.element.js | 59 +++-- src/core/core.legend.js | 130 +++++----- src/core/core.scale.js | 314 ++++++++++++------------ src/core/core.title.js | 108 ++++---- src/core/core.tooltip.js | 15 +- src/elements/element.line.js | 63 ++--- src/scales/scale.category.js | 58 +++-- src/scales/scale.linear.js | 79 +++--- src/scales/scale.linearbase.js | 64 ++--- src/scales/scale.logarithmic.js | 120 ++++----- src/scales/scale.radialLinear.js | 5 +- src/scales/scale.time.js | 252 ++++++++++--------- 22 files changed, 968 insertions(+), 881 deletions(-) diff --git a/docs/01-Chart-Configuration.md b/docs/01-Chart-Configuration.md index d88ddc736..472f17433 100644 --- a/docs/01-Chart-Configuration.md +++ b/docs/01-Chart-Configuration.md @@ -72,6 +72,7 @@ maintainAspectRatio | Boolean | true | Maintain the original canvas aspect ratio events | Array[String] | `["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"]` | Events that the chart should listen to for tooltips and hovering onClick | Function | null | Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed an array of active elements legendCallback | Function | ` function (chart) { }` | Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string. +onResize | Function | null | Called when a resize occurs. Gets passed two arguemnts: the chart instance and the new size. ### Title Configuration diff --git a/docs/09-Advanced.md b/docs/09-Advanced.md index 2641856c5..952ec88f5 100644 --- a/docs/09-Advanced.md +++ b/docs/09-Advanced.md @@ -381,6 +381,9 @@ Plugins will be called at the following times * End of update (before render occurs) * Start of draw * End of draw +* Before datasets draw +* After datasets draw +* Resize * Before an animation is started Plugins should derive from Chart.PluginBase and implement the following interface @@ -389,6 +392,8 @@ Plugins should derive from Chart.PluginBase and implement the following interfac beforeInit: function(chartInstance) { }, afterInit: function(chartInstance) { }, + resize: function(chartInstance, newChartSize) { }, + beforeUpdate: function(chartInstance) { }, afterScaleUpdate: function(chartInstance) { } afterUpdate: function(chartInstance) { }, diff --git a/src/controllers/controller.bar.js b/src/controllers/controller.bar.js index 11cb32447..28962db98 100644 --- a/src/controllers/controller.bar.js +++ b/src/controllers/controller.bar.js @@ -41,50 +41,53 @@ module.exports = function(Chart) { // Get the number of datasets that display bars. We use this to correctly calculate the bar width getBarCount: function getBarCount() { + var me = this; var barCount = 0; - helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { - var meta = this.chart.getDatasetMeta(datasetIndex); - if (meta.bar && this.chart.isDatasetVisible(datasetIndex)) { + helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) { + var meta = me.chart.getDatasetMeta(datasetIndex); + if (meta.bar && me.chart.isDatasetVisible(datasetIndex)) { ++barCount; } - }, this); + }, me); return barCount; }, update: function update(reset) { - helpers.each(this.getMeta().data, function(rectangle, index) { - this.updateElement(rectangle, index, reset); - }, this); + var me = this; + helpers.each(me.getMeta().data, function(rectangle, index) { + me.updateElement(rectangle, index, reset); + }, me); }, updateElement: function updateElement(rectangle, index, reset) { - var meta = this.getMeta(); - var xScale = this.getScaleForId(meta.xAxisID); - var yScale = this.getScaleForId(meta.yAxisID); + var me = this; + var meta = me.getMeta(); + var xScale = me.getScaleForId(meta.xAxisID); + var yScale = me.getScaleForId(meta.yAxisID); var scaleBase = yScale.getBasePixel(); - var rectangleElementOptions = this.chart.options.elements.rectangle; + var rectangleElementOptions = me.chart.options.elements.rectangle; var custom = rectangle.custom || {}; - var dataset = this.getDataset(); + var dataset = me.getDataset(); helpers.extend(rectangle, { // Utility _xScale: xScale, _yScale: yScale, - _datasetIndex: this.index, + _datasetIndex: me.index, _index: index, // Desired view properties _model: { - x: this.calculateBarX(index, this.index), - y: reset ? scaleBase : this.calculateBarY(index, this.index), + x: me.calculateBarX(index, me.index), + y: reset ? scaleBase : me.calculateBarY(index, me.index), // Tooltip - label: this.chart.data.labels[index], + label: me.chart.data.labels[index], datasetLabel: dataset.label, // Appearance - base: reset ? scaleBase : this.calculateBarBase(this.index, index), - width: this.calculateBarWidth(index), + base: reset ? scaleBase : me.calculateBarBase(me.index, index), + width: me.calculateBarWidth(index), backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor), borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleElementOptions.borderSkipped, borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor), @@ -95,12 +98,13 @@ module.exports = function(Chart) { }, calculateBarBase: function(datasetIndex, index) { - var meta = this.getMeta(); - var yScale = this.getScaleForId(meta.yAxisID); + var me = this; + var meta = me.getMeta(); + var yScale = me.getScaleForId(meta.yAxisID); var base = 0; if (yScale.options.stacked) { - var chart = this.chart; + var chart = me.chart; var datasets = chart.data.datasets; var value = datasets[datasetIndex].data[index]; @@ -129,9 +133,10 @@ module.exports = function(Chart) { }, getRuler: function(index) { - var meta = this.getMeta(); - var xScale = this.getScaleForId(meta.xAxisID); - var datasetCount = this.getBarCount(); + var me = this; + var meta = me.getMeta(); + var xScale = me.getScaleForId(meta.xAxisID); + var datasetCount = me.getBarCount(); var tickWidth; @@ -145,8 +150,8 @@ module.exports = function(Chart) { var categorySpacing = (tickWidth - (tickWidth * xScale.options.categoryPercentage)) / 2; var fullBarWidth = categoryWidth / datasetCount; - if (xScale.ticks.length !== this.chart.data.labels.length) { - var perc = xScale.ticks.length / this.chart.data.labels.length; + if (xScale.ticks.length !== me.chart.data.labels.length) { + var perc = xScale.ticks.length / me.chart.data.labels.length; fullBarWidth = fullBarWidth * perc; } @@ -186,13 +191,14 @@ module.exports = function(Chart) { }, calculateBarX: function(index, datasetIndex) { - var meta = this.getMeta(); - var xScale = this.getScaleForId(meta.xAxisID); - var barIndex = this.getBarIndex(datasetIndex); + var me = this; + var meta = me.getMeta(); + var xScale = me.getScaleForId(meta.xAxisID); + var barIndex = me.getBarIndex(datasetIndex); - var ruler = this.getRuler(index); - var leftTick = xScale.getPixelForValue(null, index, datasetIndex, this.chart.isCombo); - leftTick -= this.chart.isCombo ? (ruler.tickWidth / 2) : 0; + var ruler = me.getRuler(index); + var leftTick = xScale.getPixelForValue(null, index, datasetIndex, me.chart.isCombo); + leftTick -= me.chart.isCombo ? (ruler.tickWidth / 2) : 0; if (xScale.options.stacked) { return leftTick + (ruler.categoryWidth / 2) + ruler.categorySpacing; @@ -207,9 +213,10 @@ module.exports = function(Chart) { }, calculateBarY: function(index, datasetIndex) { - var meta = this.getMeta(); - var yScale = this.getScaleForId(meta.yAxisID); - var value = this.getDataset().data[index]; + var me = this; + var meta = me.getMeta(); + var yScale = me.getScaleForId(meta.yAxisID); + var value = me.getDataset().data[index]; if (yScale.options.stacked) { @@ -217,9 +224,9 @@ module.exports = function(Chart) { sumNeg = 0; for (var i = 0; i < datasetIndex; i++) { - var ds = this.chart.data.datasets[i]; - var dsMeta = this.chart.getDatasetMeta(i); - if (dsMeta.bar && dsMeta.yAxisID === yScale.id && this.chart.isDatasetVisible(i)) { + var ds = me.chart.data.datasets[i]; + var dsMeta = me.chart.getDatasetMeta(i); + if (dsMeta.bar && dsMeta.yAxisID === yScale.id && me.chart.isDatasetVisible(i)) { if (ds.data[index] < 0) { sumNeg += ds.data[index] || 0; } else { @@ -239,13 +246,14 @@ module.exports = function(Chart) { }, draw: function(ease) { + var me = this; var easingDecimal = ease || 1; - helpers.each(this.getMeta().data, function(rectangle, index) { - var d = this.getDataset().data[index]; + helpers.each(me.getMeta().data, function(rectangle, index) { + var d = me.getDataset().data[index]; if (d !== null && d !== undefined && !isNaN(d)) { rectangle.transition(easingDecimal).draw(); } - }, this); + }, me); }, setHoverStyle: function(rectangle) { @@ -331,33 +339,34 @@ module.exports = function(Chart) { Chart.controllers.horizontalBar = Chart.controllers.bar.extend({ updateElement: function updateElement(rectangle, index, reset, numBars) { - var meta = this.getMeta(); - var xScale = this.getScaleForId(meta.xAxisID); - var yScale = this.getScaleForId(meta.yAxisID); + var me = this; + var meta = me.getMeta(); + var xScale = me.getScaleForId(meta.xAxisID); + var yScale = me.getScaleForId(meta.yAxisID); var scaleBase = xScale.getBasePixel(); var custom = rectangle.custom || {}; - var dataset = this.getDataset(); - var rectangleElementOptions = this.chart.options.elements.rectangle; + var dataset = me.getDataset(); + var rectangleElementOptions = me.chart.options.elements.rectangle; helpers.extend(rectangle, { // Utility _xScale: xScale, _yScale: yScale, - _datasetIndex: this.index, + _datasetIndex: me.index, _index: index, // Desired view properties _model: { - x: reset ? scaleBase : this.calculateBarX(index, this.index), - y: this.calculateBarY(index, this.index), + x: reset ? scaleBase : me.calculateBarX(index, me.index), + y: me.calculateBarY(index, me.index), // Tooltip - label: this.chart.data.labels[index], + label: me.chart.data.labels[index], datasetLabel: dataset.label, // Appearance - base: reset ? scaleBase : this.calculateBarBase(this.index, index), - height: this.calculateBarHeight(index), + base: reset ? scaleBase : me.calculateBarBase(me.index, index), + height: me.calculateBarHeight(index), backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor), borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleElementOptions.borderSkipped, borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor), @@ -365,7 +374,6 @@ module.exports = function(Chart) { }, draw: function () { - var ctx = this._chart.ctx; var vm = this._view; @@ -440,27 +448,28 @@ module.exports = function(Chart) { }, calculateBarBase: function (datasetIndex, index) { - var meta = this.getMeta(); - var xScale = this.getScaleForId(meta.xAxisID); + var me = this; + var meta = me.getMeta(); + var xScale = me.getScaleForId(meta.xAxisID); var base = 0; if (xScale.options.stacked) { - var value = this.chart.data.datasets[datasetIndex].data[index]; + var value = me.chart.data.datasets[datasetIndex].data[index]; if (value < 0) { for (var i = 0; i < datasetIndex; i++) { - var negDS = this.chart.data.datasets[i]; - var negDSMeta = this.chart.getDatasetMeta(i); - if (negDSMeta.bar && negDSMeta.xAxisID === xScale.id && this.chart.isDatasetVisible(i)) { + var negDS = me.chart.data.datasets[i]; + var negDSMeta = me.chart.getDatasetMeta(i); + if (negDSMeta.bar && negDSMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(i)) { base += negDS.data[index] < 0 ? negDS.data[index] : 0; } } } else { for (var j = 0; j < datasetIndex; j++) { - var posDS = this.chart.data.datasets[j]; - var posDSMeta = this.chart.getDatasetMeta(j); - if (posDSMeta.bar && posDSMeta.xAxisID === xScale.id && this.chart.isDatasetVisible(j)) { + var posDS = me.chart.data.datasets[j]; + var posDSMeta = me.chart.getDatasetMeta(j); + if (posDSMeta.bar && posDSMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(j)) { base += posDS.data[index] > 0 ? posDS.data[index] : 0; } } @@ -473,9 +482,10 @@ module.exports = function(Chart) { }, getRuler: function (index) { - var meta = this.getMeta(); - var yScale = this.getScaleForId(meta.yAxisID); - var datasetCount = this.getBarCount(); + var me = this; + var meta = me.getMeta(); + var yScale = me.getScaleForId(meta.yAxisID); + var datasetCount = me.getBarCount(); var tickHeight; if (yScale.options.type === 'category') { @@ -488,8 +498,8 @@ module.exports = function(Chart) { var categorySpacing = (tickHeight - (tickHeight * yScale.options.categoryPercentage)) / 2; var fullBarHeight = categoryHeight / datasetCount; - if (yScale.ticks.length !== this.chart.data.labels.length) { - var perc = yScale.ticks.length / this.chart.data.labels.length; + if (yScale.ticks.length !== me.chart.data.labels.length) { + var perc = yScale.ticks.length / me.chart.data.labels.length; fullBarHeight = fullBarHeight * perc; } @@ -508,15 +518,17 @@ module.exports = function(Chart) { }, calculateBarHeight: function (index) { - var yScale = this.getScaleForId(this.getMeta().yAxisID); - var ruler = this.getRuler(index); + var me = this; + var yScale = me.getScaleForId(me.getMeta().yAxisID); + var ruler = me.getRuler(index); return yScale.options.stacked ? ruler.categoryHeight : ruler.barHeight; }, calculateBarX: function (index, datasetIndex) { - var meta = this.getMeta(); - var xScale = this.getScaleForId(meta.xAxisID); - var value = this.getDataset().data[index]; + var me = this; + var meta = me.getMeta(); + var xScale = me.getScaleForId(meta.xAxisID); + var value = me.getDataset().data[index]; if (xScale.options.stacked) { @@ -524,9 +536,9 @@ module.exports = function(Chart) { sumNeg = 0; for (var i = 0; i < datasetIndex; i++) { - var ds = this.chart.data.datasets[i]; - var dsMeta = this.chart.getDatasetMeta(i); - if (dsMeta.bar && dsMeta.xAxisID === xScale.id && this.chart.isDatasetVisible(i)) { + var ds = me.chart.data.datasets[i]; + var dsMeta = me.chart.getDatasetMeta(i); + if (dsMeta.bar && dsMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(i)) { if (ds.data[index] < 0) { sumNeg += ds.data[index] || 0; } else { @@ -546,13 +558,14 @@ module.exports = function(Chart) { }, calculateBarY: function (index, datasetIndex) { - var meta = this.getMeta(); - var yScale = this.getScaleForId(meta.yAxisID); - var barIndex = this.getBarIndex(datasetIndex); - - var ruler = this.getRuler(index); - var topTick = yScale.getPixelForValue(null, index, datasetIndex, this.chart.isCombo); - topTick -= this.chart.isCombo ? (ruler.tickHeight / 2) : 0; + var me = this; + var meta = me.getMeta(); + var yScale = me.getScaleForId(meta.yAxisID); + var barIndex = me.getBarIndex(datasetIndex); + + var ruler = me.getRuler(index); + var topTick = yScale.getPixelForValue(null, index, datasetIndex, me.chart.isCombo); + topTick -= me.chart.isCombo ? (ruler.tickHeight / 2) : 0; if (yScale.options.stacked) { return topTick + (ruler.categoryHeight / 2) + ruler.categorySpacing; diff --git a/src/controllers/controller.doughnut.js b/src/controllers/controller.doughnut.js index 423d767a1..ddc1b9af4 100644 --- a/src/controllers/controller.doughnut.js +++ b/src/controllers/controller.doughnut.js @@ -132,8 +132,8 @@ module.exports = function(Chart) { }, update: function update(reset) { - var _this = this; - var chart = _this.chart, + var me = this; + var chart = me.chart, chartArea = chart.chartArea, opts = chart.options, arcOpts = opts.elements.arc, @@ -144,7 +144,7 @@ module.exports = function(Chart) { x: 0, y: 0 }, - meta = _this.getMeta(), + meta = me.getMeta(), cutoutPercentage = opts.cutoutPercentage, circumference = opts.circumference; @@ -173,19 +173,19 @@ module.exports = function(Chart) { chart.offsetX = offset.x * chart.outerRadius; chart.offsetY = offset.y * chart.outerRadius; - meta.total = _this.calculateTotal(); + meta.total = me.calculateTotal(); - _this.outerRadius = chart.outerRadius - (chart.radiusLength * _this.getRingIndex(_this.index)); - _this.innerRadius = _this.outerRadius - chart.radiusLength; + me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index)); + me.innerRadius = me.outerRadius - chart.radiusLength; helpers.each(meta.data, function(arc, index) { - _this.updateElement(arc, index, reset); + me.updateElement(arc, index, reset); }); }, updateElement: function(arc, index, reset) { - var _this = this; - var chart = _this.chart, + var me = this; + var chart = me.chart, chartArea = chart.chartArea, opts = chart.options, animationOpts = opts.animation, @@ -194,16 +194,16 @@ module.exports = function(Chart) { centerY = (chartArea.top + chartArea.bottom) / 2, startAngle = opts.rotation, // non reset case handled later endAngle = opts.rotation, // non reset case handled later - dataset = _this.getDataset(), - circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : _this.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)), - innerRadius = reset && animationOpts.animateScale ? 0 : _this.innerRadius, - outerRadius = reset && animationOpts.animateScale ? 0 : _this.outerRadius, + dataset = me.getDataset(), + circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)), + innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius, + outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius, custom = arc.custom || {}, valueAtIndexOrDefault = helpers.getValueAtIndexOrDefault; helpers.extend(arc, { // Utility - _datasetIndex: _this.index, + _datasetIndex: me.index, _index: index, // Desired view properties @@ -228,7 +228,7 @@ module.exports = function(Chart) { if (index === 0) { model.startAngle = opts.rotation; } else { - model.startAngle = _this.getMeta().data[index - 1]._model.endAngle; + model.startAngle = me.getMeta().data[index - 1]._model.endAngle; } model.endAngle = model.startAngle + model.circumference; diff --git a/src/controllers/controller.line.js b/src/controllers/controller.line.js index 48cae30a9..679104c69 100644 --- a/src/controllers/controller.line.js +++ b/src/controllers/controller.line.js @@ -260,7 +260,7 @@ module.exports = function(Chart) { draw: function(ease) { var me = this; - var meta = this.getMeta(); + var meta = me.getMeta(); var points = meta.data || []; var easingDecimal = ease || 1; var i, ilen; diff --git a/src/controllers/controller.polarArea.js b/src/controllers/controller.polarArea.js index 0577fbeed..ebf88b5ea 100644 --- a/src/controllers/controller.polarArea.js +++ b/src/controllers/controller.polarArea.js @@ -106,10 +106,10 @@ module.exports = function(Chart) { linkScales: helpers.noop, update: function update(reset) { - var _this = this; - var chart = _this.chart; + var me = this; + var chart = me.chart; var chartArea = chart.chartArea; - var meta = _this.getMeta(); + var meta = me.getMeta(); var opts = chart.options; var arcOpts = opts.elements.arc; var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); @@ -117,21 +117,21 @@ module.exports = function(Chart) { chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); - _this.outerRadius = chart.outerRadius - (chart.radiusLength * _this.index); - _this.innerRadius = _this.outerRadius - chart.radiusLength; + me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index); + me.innerRadius = me.outerRadius - chart.radiusLength; - meta.count = _this.countVisibleElements(); + meta.count = me.countVisibleElements(); helpers.each(meta.data, function(arc, index) { - _this.updateElement(arc, index, reset); + me.updateElement(arc, index, reset); }); }, updateElement: function(arc, index, reset) { - var _this = this; - var chart = _this.chart; + var me = this; + var chart = me.chart; var chartArea = chart.chartArea; - var dataset = _this.getDataset(); + var dataset = me.getDataset(); var opts = chart.options; var animationOpts = opts.animation; var arcOpts = opts.elements.arc; @@ -140,14 +140,14 @@ module.exports = function(Chart) { var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault; var labels = chart.data.labels; - var circumference = _this.calculateCircumference(dataset.data[index]); + var circumference = me.calculateCircumference(dataset.data[index]); var centerX = (chartArea.left + chartArea.right) / 2; var centerY = (chartArea.top + chartArea.bottom) / 2; // If there is NaN data before us, we need to calculate the starting angle correctly. // We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data var visibleCount = 0; - var meta = _this.getMeta(); + var meta = me.getMeta(); for (var i = 0; i < index; ++i) { if (!isNaN(dataset.data[i]) && !meta.data[i].hidden) { ++visibleCount; @@ -163,7 +163,7 @@ module.exports = function(Chart) { helpers.extend(arc, { // Utility - _datasetIndex: _this.index, + _datasetIndex: me.index, _index: index, _scale: scale, @@ -180,7 +180,7 @@ module.exports = function(Chart) { }); // Apply border and fill style - _this.removeHoverStyle(arc); + me.removeHoverStyle(arc); arc.pivot(); }, diff --git a/src/controllers/controller.radar.js b/src/controllers/controller.radar.js index 6dcd976ce..102c3744a 100644 --- a/src/controllers/controller.radar.js +++ b/src/controllers/controller.radar.js @@ -31,13 +31,14 @@ module.exports = function(Chart) { }, update: function update(reset) { - var meta = this.getMeta(); + var me = this; + var meta = me.getMeta(); var line = meta.dataset; var points = meta.data; var custom = line.custom || {}; - var dataset = this.getDataset(); - var lineElementOptions = this.chart.options.elements.line; - var scale = this.chart.scale; + var dataset = me.getDataset(); + var lineElementOptions = me.chart.options.elements.line; + var scale = me.chart.scale; // Compatibility: If the properties are defined with only the old name, use those values if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { @@ -46,7 +47,7 @@ module.exports = function(Chart) { helpers.extend(meta.dataset, { // Utility - _datasetIndex: this.index, + _datasetIndex: me.index, // Data _children: points, _loop: true, @@ -74,23 +75,24 @@ module.exports = function(Chart) { // Update Points helpers.each(points, function(point, index) { - this.updateElement(point, index, reset); - }, this); + me.updateElement(point, index, reset); + }, me); // Update bezier control points - this.updateBezierControlPoints(); + me.updateBezierControlPoints(); }, updateElement: function(point, index, reset) { + var me = this; var custom = point.custom || {}; - var dataset = this.getDataset(); - var scale = this.chart.scale; - var pointElementOptions = this.chart.options.elements.point; + var dataset = me.getDataset(); + var scale = me.chart.scale; + var pointElementOptions = me.chart.options.elements.point; var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]); helpers.extend(point, { // Utility - _datasetIndex: this.index, + _datasetIndex: me.index, _index: index, _scale: scale, @@ -100,7 +102,7 @@ module.exports = function(Chart) { y: reset ? scale.yCenter : pointPosition.y, // Appearance - tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.tension, this.chart.options.elements.line.tension), + tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.tension, me.chart.options.elements.line.tension), radius: custom.radius ? custom.radius : helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius), backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor), borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor), @@ -136,7 +138,7 @@ module.exports = function(Chart) { // Now pivot the point for animation point.pivot(); - }, this); + }); }, draw: function(ease) { diff --git a/src/core/core.animation.js b/src/core/core.animation.js index f1c4a71f1..17c0f6597 100644 --- a/src/core/core.animation.js +++ b/src/core/core.animation.js @@ -28,27 +28,28 @@ module.exports = function(Chart) { dropFrames: 0, request: null, addAnimation: function(chartInstance, animationObject, duration, lazy) { + var me = this; if (!lazy) { chartInstance.animating = true; } - for (var index = 0; index < this.animations.length; ++index) { - if (this.animations[index].chartInstance === chartInstance) { + for (var index = 0; index < me.animations.length; ++index) { + if (me.animations[index].chartInstance === chartInstance) { // replacing an in progress animation - this.animations[index].animationObject = animationObject; + me.animations[index].animationObject = animationObject; return; } } - this.animations.push({ + me.animations.push({ chartInstance: chartInstance, animationObject: animationObject }); // If there are no animations queued, manually kickstart a digest, for lack of a better word - if (this.animations.length === 1) { - this.requestAnimationFrame(); + if (me.animations.length === 1) { + me.requestAnimationFrame(); } }, // Cancel the animation for a given chart instance @@ -75,54 +76,55 @@ module.exports = function(Chart) { } }, startDigest: function() { + var me = this; var startTime = Date.now(); var framesToDrop = 0; - if (this.dropFrames > 1) { - framesToDrop = Math.floor(this.dropFrames); - this.dropFrames = this.dropFrames % 1; + if (me.dropFrames > 1) { + framesToDrop = Math.floor(me.dropFrames); + me.dropFrames = me.dropFrames % 1; } var i = 0; - while (i < this.animations.length) { - if (this.animations[i].animationObject.currentStep === null) { - this.animations[i].animationObject.currentStep = 0; + while (i < me.animations.length) { + if (me.animations[i].animationObject.currentStep === null) { + me.animations[i].animationObject.currentStep = 0; } - this.animations[i].animationObject.currentStep += 1 + framesToDrop; + me.animations[i].animationObject.currentStep += 1 + framesToDrop; - if (this.animations[i].animationObject.currentStep > this.animations[i].animationObject.numSteps) { - this.animations[i].animationObject.currentStep = this.animations[i].animationObject.numSteps; + if (me.animations[i].animationObject.currentStep > me.animations[i].animationObject.numSteps) { + me.animations[i].animationObject.currentStep = me.animations[i].animationObject.numSteps; } - this.animations[i].animationObject.render(this.animations[i].chartInstance, this.animations[i].animationObject); - if (this.animations[i].animationObject.onAnimationProgress && this.animations[i].animationObject.onAnimationProgress.call) { - this.animations[i].animationObject.onAnimationProgress.call(this.animations[i].chartInstance, this.animations[i]); + me.animations[i].animationObject.render(me.animations[i].chartInstance, me.animations[i].animationObject); + if (me.animations[i].animationObject.onAnimationProgress && me.animations[i].animationObject.onAnimationProgress.call) { + me.animations[i].animationObject.onAnimationProgress.call(me.animations[i].chartInstance, me.animations[i]); } - if (this.animations[i].animationObject.currentStep === this.animations[i].animationObject.numSteps) { - if (this.animations[i].animationObject.onAnimationComplete && this.animations[i].animationObject.onAnimationComplete.call) { - this.animations[i].animationObject.onAnimationComplete.call(this.animations[i].chartInstance, this.animations[i]); + if (me.animations[i].animationObject.currentStep === me.animations[i].animationObject.numSteps) { + if (me.animations[i].animationObject.onAnimationComplete && me.animations[i].animationObject.onAnimationComplete.call) { + me.animations[i].animationObject.onAnimationComplete.call(me.animations[i].chartInstance, me.animations[i]); } // executed the last frame. Remove the animation. - this.animations[i].chartInstance.animating = false; + me.animations[i].chartInstance.animating = false; - this.animations.splice(i, 1); + me.animations.splice(i, 1); } else { ++i; } } var endTime = Date.now(); - var dropFrames = (endTime - startTime) / this.frameDuration; + var dropFrames = (endTime - startTime) / me.frameDuration; - this.dropFrames += dropFrames; + me.dropFrames += dropFrames; // Do we have more stuff to animate? - if (this.animations.length > 0) { - this.requestAnimationFrame(); + if (me.animations.length > 0) { + me.requestAnimationFrame(); } } }; diff --git a/src/core/core.controller.js b/src/core/core.controller.js index 0e103d2bd..c7861c236 100644 --- a/src/core/core.controller.js +++ b/src/core/core.controller.js @@ -43,25 +43,26 @@ module.exports = function(Chart) { helpers.extend(Chart.Controller.prototype, { initialize: function initialize() { + var me = this; // Before init plugin notification - Chart.pluginService.notifyPlugins('beforeInit', [this]); + Chart.pluginService.notifyPlugins('beforeInit', [me]); - this.bindEvents(); + me.bindEvents(); // Make sure controllers are built first so that each dataset is bound to an axis before the scales // are built - this.ensureScalesHaveIDs(); - this.buildOrUpdateControllers(); - this.buildScales(); - this.updateLayout(); - this.resetElements(); - this.initToolTip(); - this.update(); + me.ensureScalesHaveIDs(); + me.buildOrUpdateControllers(); + me.buildScales(); + me.updateLayout(); + me.resetElements(); + me.initToolTip(); + me.update(); // After init plugin notification - Chart.pluginService.notifyPlugins('afterInit', [this]); + Chart.pluginService.notifyPlugins('afterInit', [me]); - return this; + return me; }, clear: function clear() { @@ -76,26 +77,39 @@ module.exports = function(Chart) { }, resize: function resize(silent) { - var canvas = this.chart.canvas; - var newWidth = helpers.getMaximumWidth(this.chart.canvas); - var newHeight = (this.options.maintainAspectRatio && isNaN(this.chart.aspectRatio) === false && isFinite(this.chart.aspectRatio) && this.chart.aspectRatio !== 0) ? newWidth / this.chart.aspectRatio : helpers.getMaximumHeight(this.chart.canvas); + var me = this; + var chart = me.chart; + var canvas = chart.canvas; + var newWidth = helpers.getMaximumWidth(canvas); + var aspectRatio = chart.aspectRatio; + var newHeight = (me.options.maintainAspectRatio && isNaN(aspectRatio) === false && isFinite(aspectRatio) && aspectRatio !== 0) ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas); - var sizeChanged = this.chart.width !== newWidth || this.chart.height !== newHeight; + var sizeChanged = chart.width !== newWidth || chart.height !== newHeight; - if (!sizeChanged) - return this; + if (!sizeChanged) { + return me; + } + + canvas.width = chart.width = newWidth; + canvas.height = chart.height = newHeight; - canvas.width = this.chart.width = newWidth; - canvas.height = this.chart.height = newHeight; + helpers.retinaScale(chart); - helpers.retinaScale(this.chart); + // Notify any plugins about the resize + var newSize = { width: newWidth, height: newHeight }; + Chart.pluginService.notifyPlugins('resize', [me, newSize]); + + // Notify of resize + if (me.options.onResize) { + me.options.onResize(me, newSize); + } if (!silent) { - this.stop(); - this.update(this.options.responsiveAnimationDuration); + me.stop(); + me.update(me.options.responsiveAnimationDuration); } - return this; + return me; }, ensureScalesHaveIDs: function ensureScalesHaveIDs() { @@ -170,13 +184,14 @@ module.exports = function(Chart) { }, buildOrUpdateControllers: function buildOrUpdateControllers() { + var me = this; var types = []; var newControllers = []; - helpers.each(this.data.datasets, function(dataset, datasetIndex) { - var meta = this.getDatasetMeta(datasetIndex); + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + var meta = me.getDatasetMeta(datasetIndex); if (!meta.type) { - meta.type = dataset.type || this.config.type; + meta.type = dataset.type || me.config.type; } types.push(meta.type); @@ -184,15 +199,15 @@ module.exports = function(Chart) { if (meta.controller) { meta.controller.updateIndex(datasetIndex); } else { - meta.controller = new Chart.controllers[meta.type](this, datasetIndex); + meta.controller = new Chart.controllers[meta.type](me, datasetIndex); newControllers.push(meta.controller); } - }, this); + }, me); if (types.length > 1) { for (var i = 1; i < types.length; i++) { if (types[i] !== types[i - 1]) { - this.isCombo = true; + me.isCombo = true; break; } } @@ -202,29 +217,31 @@ module.exports = function(Chart) { }, resetElements: function resetElements() { - helpers.each(this.data.datasets, function(dataset, datasetIndex) { - this.getDatasetMeta(datasetIndex).controller.reset(); - }, this); + var me = this; + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + me.getDatasetMeta(datasetIndex).controller.reset(); + }, me); }, update: function update(animationDuration, lazy) { - Chart.pluginService.notifyPlugins('beforeUpdate', [this]); + var me = this; + Chart.pluginService.notifyPlugins('beforeUpdate', [me]); // In case the entire data object changed - this.tooltip._data = this.data; + me.tooltip._data = me.data; // Make sure dataset controllers are updated and new controllers are reset - var newControllers = this.buildOrUpdateControllers(); + var newControllers = me.buildOrUpdateControllers(); // Make sure all dataset controllers have correct meta data counts - helpers.each(this.data.datasets, function(dataset, datasetIndex) { - this.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements(); - }, this); + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements(); + }, me); - Chart.layoutService.update(this, this.chart.width, this.chart.height); + Chart.layoutService.update(me, me.chart.width, me.chart.height); // Apply changes to the dataets that require the scales to have been calculated i.e BorderColor chages - Chart.pluginService.notifyPlugins('afterScaleUpdate', [this]); + Chart.pluginService.notifyPlugins('afterScaleUpdate', [me]); // Can only reset the new controllers after the scales have been updated helpers.each(newControllers, function(controller) { @@ -232,20 +249,21 @@ module.exports = function(Chart) { }); // This will loop through any data and do the appropriate element update for the type - helpers.each(this.data.datasets, function(dataset, datasetIndex) { - this.getDatasetMeta(datasetIndex).controller.update(); - }, this); + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + me.getDatasetMeta(datasetIndex).controller.update(); + }, me); // Do this before render so that any plugins that need final scale updates can use it - Chart.pluginService.notifyPlugins('afterUpdate', [this]); + Chart.pluginService.notifyPlugins('afterUpdate', [me]); - this.render(animationDuration, lazy); + me.render(animationDuration, lazy); }, render: function render(duration, lazy) { - Chart.pluginService.notifyPlugins('beforeRender', [this]); + var me = this; + Chart.pluginService.notifyPlugins('beforeRender', [me]); - var animationOptions = this.options.animation; + var animationOptions = me.options.animation; if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) { var animation = new Chart.Animation(); animation.numSteps = (duration || animationOptions.duration) / 16.66; //60 fps @@ -264,56 +282,58 @@ module.exports = function(Chart) { animation.onAnimationProgress = animationOptions.onProgress; animation.onAnimationComplete = animationOptions.onComplete; - Chart.animationService.addAnimation(this, animation, duration, lazy); + Chart.animationService.addAnimation(me, animation, duration, lazy); } else { - this.draw(); + me.draw(); if (animationOptions && animationOptions.onComplete && animationOptions.onComplete.call) { - animationOptions.onComplete.call(this); + animationOptions.onComplete.call(me); } } - return this; + return me; }, draw: function(ease) { + var me = this; var easingDecimal = ease || 1; - this.clear(); + me.clear(); - Chart.pluginService.notifyPlugins('beforeDraw', [this, easingDecimal]); + Chart.pluginService.notifyPlugins('beforeDraw', [me, easingDecimal]); // Draw all the scales - helpers.each(this.boxes, function(box) { - box.draw(this.chartArea); - }, this); - if (this.scale) { - this.scale.draw(); + helpers.each(me.boxes, function(box) { + box.draw(me.chartArea); + }, me); + if (me.scale) { + me.scale.draw(); } - Chart.pluginService.notifyPlugins('beforeDatasetDraw', [this, easingDecimal]); + Chart.pluginService.notifyPlugins('beforeDatasetDraw', [me, easingDecimal]); // Draw each dataset via its respective controller (reversed to support proper line stacking) - helpers.each(this.data.datasets, function(dataset, datasetIndex) { - if (this.isDatasetVisible(datasetIndex)) { - this.getDatasetMeta(datasetIndex).controller.draw(ease); + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + if (me.isDatasetVisible(datasetIndex)) { + me.getDatasetMeta(datasetIndex).controller.draw(ease); } - }, this, true); + }, me, true); - Chart.pluginService.notifyPlugins('afterDatasetDraw', [this, easingDecimal]); + Chart.pluginService.notifyPlugins('afterDatasetDraw', [me, easingDecimal]); // Finally draw the tooltip - this.tooltip.transition(easingDecimal).draw(); + me.tooltip.transition(easingDecimal).draw(); - Chart.pluginService.notifyPlugins('afterDraw', [this, easingDecimal]); + Chart.pluginService.notifyPlugins('afterDraw', [me, easingDecimal]); }, // Get the single element that was clicked on // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw getElementAtEvent: function(e) { - var eventPosition = helpers.getRelativePosition(e, this.chart); + var me = this; + var eventPosition = helpers.getRelativePosition(e, me.chart); var elementsArray = []; - helpers.each(this.data.datasets, function(dataset, datasetIndex) { - if (this.isDatasetVisible(datasetIndex)) { - var meta = this.getDatasetMeta(datasetIndex); + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + if (me.isDatasetVisible(datasetIndex)) { + var meta = me.getDatasetMeta(datasetIndex); helpers.each(meta.data, function(element, index) { if (element.inRange(eventPosition.x, eventPosition.y)) { elementsArray.push(element); @@ -321,20 +341,21 @@ module.exports = function(Chart) { } }); } - }, this); + }); return elementsArray; }, getElementsAtEvent: function(e) { - var eventPosition = helpers.getRelativePosition(e, this.chart); + var me = this; + var eventPosition = helpers.getRelativePosition(e, me.chart); var elementsArray = []; var found = (function() { - if (this.data.datasets) { - for (var i = 0; i < this.data.datasets.length; i++) { - var meta = this.getDatasetMeta(i); - if (this.isDatasetVisible(i)) { + if (me.data.datasets) { + for (var i = 0; i < me.data.datasets.length; i++) { + var meta = me.getDatasetMeta(i); + if (me.isDatasetVisible(i)) { for (var j = 0; j < meta.data.length; j++) { if (meta.data[j].inRange(eventPosition.x, eventPosition.y)) { return meta.data[j]; @@ -343,18 +364,18 @@ module.exports = function(Chart) { } } } - }).call(this); + }).call(me); if (!found) { return elementsArray; } - helpers.each(this.data.datasets, function(dataset, datasetIndex) { - if (this.isDatasetVisible(datasetIndex)) { - var meta = this.getDatasetMeta(datasetIndex); + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + if (me.isDatasetVisible(datasetIndex)) { + var meta = me.getDatasetMeta(datasetIndex); elementsArray.push(meta.data[found._index]); } - }, this); + }, me); return elementsArray; }, @@ -384,14 +405,15 @@ module.exports = function(Chart) { }, getDatasetMeta: function(datasetIndex) { - var dataset = this.data.datasets[datasetIndex]; + var me = this; + var dataset = me.data.datasets[datasetIndex]; if (!dataset._meta) { dataset._meta = {}; } - var meta = dataset._meta[this.id]; + var meta = dataset._meta[me.id]; if (!meta) { - meta = dataset._meta[this.id] = { + meta = dataset._meta[me.id] = { type: null, data: [], dataset: null, @@ -428,28 +450,29 @@ module.exports = function(Chart) { }, destroy: function destroy() { - this.stop(); - this.clear(); - helpers.unbindEvents(this, this.events); - helpers.removeResizeListener(this.chart.canvas.parentNode); + var me = this; + me.stop(); + me.clear(); + helpers.unbindEvents(me, me.events); + helpers.removeResizeListener(me.chart.canvas.parentNode); // Reset canvas height/width attributes - var canvas = this.chart.canvas; - canvas.width = this.chart.width; - canvas.height = this.chart.height; + var canvas = me.chart.canvas; + canvas.width = me.chart.width; + canvas.height = me.chart.height; // if we scaled the canvas in response to a devicePixelRatio !== 1, we need to undo that transform here - if (this.chart.originalDevicePixelRatio !== undefined) { - this.chart.ctx.scale(1 / this.chart.originalDevicePixelRatio, 1 / this.chart.originalDevicePixelRatio); + if (me.chart.originalDevicePixelRatio !== undefined) { + me.chart.ctx.scale(1 / me.chart.originalDevicePixelRatio, 1 / me.chart.originalDevicePixelRatio); } // Reset to the old style since it may have been changed by the device pixel ratio changes - canvas.style.width = this.chart.originalCanvasStyleWidth; - canvas.style.height = this.chart.originalCanvasStyleHeight; + canvas.style.width = me.chart.originalCanvasStyleWidth; + canvas.style.height = me.chart.originalCanvasStyleHeight; - Chart.pluginService.notifyPlugins('destroy', [this]); + Chart.pluginService.notifyPlugins('destroy', [me]); - delete Chart.instances[this.id]; + delete Chart.instances[me.id]; }, toBase64Image: function toBase64Image() { @@ -457,17 +480,19 @@ module.exports = function(Chart) { }, initToolTip: function initToolTip() { - this.tooltip = new Chart.Tooltip({ - _chart: this.chart, - _chartInstance: this, - _data: this.data, - _options: this.options.tooltips - }, this); + var me = this; + me.tooltip = new Chart.Tooltip({ + _chart: me.chart, + _chartInstance: me, + _data: me.data, + _options: me.options.tooltips + }, me); }, bindEvents: function bindEvents() { - helpers.bindEvents(this, this.options.events, function(evt) { - this.eventHandler(evt); + var me = this; + helpers.bindEvents(me, me.options.events, function(evt) { + me.eventHandler(evt); }); }, diff --git a/src/core/core.datasetController.js b/src/core/core.datasetController.js index f4d213eca..07f787eaf 100644 --- a/src/core/core.datasetController.js +++ b/src/core/core.datasetController.js @@ -25,10 +25,11 @@ module.exports = function(Chart) { dataElementType: null, initialize: function(chart, datasetIndex) { - this.chart = chart; - this.index = datasetIndex; - this.linkScales(); - this.addElements(); + var me = this; + me.chart = chart; + me.index = datasetIndex; + me.linkScales(); + me.addElements(); }, updateIndex: function(datasetIndex) { @@ -36,14 +37,15 @@ module.exports = function(Chart) { }, linkScales: function() { - var meta = this.getMeta(); - var dataset = this.getDataset(); + var me = this; + var meta = me.getMeta(); + var dataset = me.getDataset(); if (meta.xAxisID === null) { - meta.xAxisID = dataset.xAxisID || this.chart.options.scales.xAxes[0].id; + meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id; } if (meta.yAxisID === null) { - meta.yAxisID = dataset.yAxisID || this.chart.options.scales.yAxes[0].id; + meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id; } }, diff --git a/src/core/core.element.js b/src/core/core.element.js index fd495b08a..5bab6d49c 100644 --- a/src/core/core.element.js +++ b/src/core/core.element.js @@ -10,81 +10,90 @@ module.exports = function(Chart) { helpers.extend(this, configuration); this.initialize.apply(this, arguments); }; + helpers.extend(Chart.Element.prototype, { + initialize: function() { this.hidden = false; }, + pivot: function() { - if (!this._view) { - this._view = helpers.clone(this._model); + var me = this; + if (!me._view) { + me._view = helpers.clone(me._model); } - this._start = helpers.clone(this._view); - return this; + me._start = helpers.clone(me._view); + return me; }, + transition: function(ease) { - if (!this._view) { - this._view = helpers.clone(this._model); + var me = this; + + if (!me._view) { + me._view = helpers.clone(me._model); } // No animation -> No Transition if (ease === 1) { - this._view = this._model; - this._start = null; - return this; + me._view = me._model; + me._start = null; + return me; } - if (!this._start) { - this.pivot(); + if (!me._start) { + me.pivot(); } - helpers.each(this._model, function(value, key) { + helpers.each(me._model, function(value, key) { if (key[0] === '_') { // Only non-underscored properties } // Init if doesn't exist - else if (!this._view.hasOwnProperty(key)) { - if (typeof value === 'number' && !isNaN(this._view[key])) { - this._view[key] = value * ease; + else if (!me._view.hasOwnProperty(key)) { + if (typeof value === 'number' && !isNaN(me._view[key])) { + me._view[key] = value * ease; } else { - this._view[key] = value; + me._view[key] = value; } } // No unnecessary computations - else if (value === this._view[key]) { + else if (value === me._view[key]) { // It's the same! Woohoo! } // Color transitions if possible else if (typeof value === 'string') { try { - var color = helpers.color(this._model[key]).mix(helpers.color(this._start[key]), ease); - this._view[key] = color.rgbString(); + var color = helpers.color(me._model[key]).mix(helpers.color(me._start[key]), ease); + me._view[key] = color.rgbString(); } catch (err) { - this._view[key] = value; + me._view[key] = value; } } // Number transitions else if (typeof value === 'number') { - var startVal = this._start[key] !== undefined && isNaN(this._start[key]) === false ? this._start[key] : 0; - this._view[key] = ((this._model[key] - startVal) * ease) + startVal; + var startVal = me._start[key] !== undefined && isNaN(me._start[key]) === false ? me._start[key] : 0; + me._view[key] = ((me._model[key] - startVal) * ease) + startVal; } // Everything else else { - this._view[key] = value; + me._view[key] = value; } - }, this); + }, me); - return this; + return me; }, + tooltipPosition: function() { return { x: this._model.x, y: this._model.y }; }, + hasValue: function() { return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y); } diff --git a/src/core/core.legend.js b/src/core/core.legend.js index f625bb881..1aa3fa2f3 100644 --- a/src/core/core.legend.js +++ b/src/core/core.legend.js @@ -44,7 +44,7 @@ module.exports = function(Chart) { return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) { return { text: dataset.label, - fillStyle: dataset.backgroundColor, + fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]), hidden: !chart.isDatasetVisible(i), lineCap: dataset.borderCapStyle, lineDash: dataset.borderDash, @@ -79,32 +79,33 @@ module.exports = function(Chart) { beforeUpdate: noop, update: function(maxWidth, maxHeight, margins) { + var me = this; // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) - this.beforeUpdate(); + me.beforeUpdate(); // Absorb the master measurements - this.maxWidth = maxWidth; - this.maxHeight = maxHeight; - this.margins = margins; + me.maxWidth = maxWidth; + me.maxHeight = maxHeight; + me.margins = margins; // Dimensions - this.beforeSetDimensions(); - this.setDimensions(); - this.afterSetDimensions(); + me.beforeSetDimensions(); + me.setDimensions(); + me.afterSetDimensions(); // Labels - this.beforeBuildLabels(); - this.buildLabels(); - this.afterBuildLabels(); + me.beforeBuildLabels(); + me.buildLabels(); + me.afterBuildLabels(); // Fit - this.beforeFit(); - this.fit(); - this.afterFit(); + me.beforeFit(); + me.fit(); + me.afterFit(); // - this.afterUpdate(); + me.afterUpdate(); - return this.minSize; + return me.minSize; }, afterUpdate: noop, @@ -112,28 +113,29 @@ module.exports = function(Chart) { beforeSetDimensions: noop, setDimensions: function() { + var me = this; // Set the unconstrained dimension before label rotation - if (this.isHorizontal()) { + if (me.isHorizontal()) { // Reset position before calculating rotation - this.width = this.maxWidth; - this.left = 0; - this.right = this.width; + me.width = me.maxWidth; + me.left = 0; + me.right = me.width; } else { - this.height = this.maxHeight; + me.height = me.maxHeight; // Reset position before calculating rotation - this.top = 0; - this.bottom = this.height; + me.top = 0; + me.bottom = me.height; } // Reset padding - this.paddingLeft = 0; - this.paddingTop = 0; - this.paddingRight = 0; - this.paddingBottom = 0; + me.paddingLeft = 0; + me.paddingTop = 0; + me.paddingRight = 0; + me.paddingBottom = 0; // Reset minSize - this.minSize = { + me.minSize = { width: 0, height: 0 }; @@ -144,9 +146,10 @@ module.exports = function(Chart) { beforeBuildLabels: noop, buildLabels: function() { - this.legendItems = this.options.labels.generateLabels.call(this, this.chart); - if(this.options.reverse){ - this.legendItems.reverse(); + var me = this; + me.legendItems = me.options.labels.generateLabels.call(me, me.chart); + if(me.options.reverse){ + me.legendItems.reverse(); } }, afterBuildLabels: noop, @@ -155,11 +158,12 @@ module.exports = function(Chart) { beforeFit: noop, fit: function() { - var opts = this.options; + var me = this; + var opts = me.options; var labelOpts = opts.labels; var display = opts.display; - var ctx = this.ctx; + var ctx = me.ctx; var globalDefault = Chart.defaults.global, itemOrDefault = helpers.getValueOrDefault, @@ -169,17 +173,17 @@ module.exports = function(Chart) { labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); // Reset hit boxes - var hitboxes = this.legendHitBoxes = []; + var hitboxes = me.legendHitBoxes = []; - var minSize = this.minSize; - var isHorizontal = this.isHorizontal(); + var minSize = me.minSize; + var isHorizontal = me.isHorizontal(); if (isHorizontal) { - minSize.width = this.maxWidth; // fill all the width + minSize.width = me.maxWidth; // fill all the width minSize.height = display ? 10 : 0; } else { minSize.width = display ? 10 : 0; - minSize.height = this.maxHeight; // fill all the height + minSize.height = me.maxHeight; // fill all the height } // Increase sizes here @@ -188,18 +192,18 @@ module.exports = function(Chart) { // Labels // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one - var lineWidths = this.lineWidths = [0]; - var totalHeight = this.legendItems.length ? fontSize + (labelOpts.padding) : 0; + var lineWidths = me.lineWidths = [0]; + var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0; ctx.textAlign = "left"; ctx.textBaseline = 'top'; ctx.font = labelFont; - helpers.each(this.legendItems, function(legendItem, i) { + helpers.each(me.legendItems, function(legendItem, i) { var width = labelOpts.boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; - if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= this.width) { + if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) { totalHeight += fontSize + (labelOpts.padding); - lineWidths[lineWidths.length] = this.left; + lineWidths[lineWidths.length] = me.left; } // Store the hitbox width and height here. Final position will be updated in `draw` @@ -211,7 +215,7 @@ module.exports = function(Chart) { }; lineWidths[lineWidths.length - 1] += width + labelOpts.padding; - }, this); + }, me); minSize.height += totalHeight; @@ -220,8 +224,8 @@ module.exports = function(Chart) { } } - this.width = minSize.width; - this.height = minSize.height; + me.width = minSize.width; + me.height = minSize.height; }, afterFit: noop, @@ -232,18 +236,19 @@ module.exports = function(Chart) { // Actualy draw the legend on the canvas draw: function() { - var opts = this.options; + var me = this; + var opts = me.options; var labelOpts = opts.labels; var globalDefault = Chart.defaults.global, lineDefault = globalDefault.elements.line, - legendWidth = this.width, - lineWidths = this.lineWidths; + legendWidth = me.width, + lineWidths = me.lineWidths; if (opts.display) { - var ctx = this.ctx, + var ctx = me.ctx, cursor = { - x: this.left + ((legendWidth - lineWidths[0]) / 2), - y: this.top + labelOpts.padding, + x: me.left + ((legendWidth - lineWidths[0]) / 2), + y: me.top + labelOpts.padding, line: 0 }, itemOrDefault = helpers.getValueOrDefault, @@ -254,7 +259,7 @@ module.exports = function(Chart) { labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); // Horizontal - if (this.isHorizontal()) { + if (me.isHorizontal()) { // Labels ctx.textAlign = "left"; ctx.textBaseline = 'top'; @@ -264,9 +269,9 @@ module.exports = function(Chart) { ctx.font = labelFont; var boxWidth = labelOpts.boxWidth, - hitboxes = this.legendHitBoxes; + hitboxes = me.legendHitBoxes; - helpers.each(this.legendItems, function(legendItem, i) { + helpers.each(me.legendItems, function(legendItem, i) { var textWidth = ctx.measureText(legendItem.text).width, width = boxWidth + (fontSize / 2) + textWidth, x = cursor.x, @@ -275,7 +280,7 @@ module.exports = function(Chart) { if (x + width >= legendWidth) { y = cursor.y += fontSize + (labelOpts.padding); cursor.line++; - x = cursor.x = this.left + ((legendWidth - lineWidths[cursor.line]) / 2); + x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2); } // Set the ctx for the box @@ -315,7 +320,7 @@ module.exports = function(Chart) { } cursor.x += width + (labelOpts.padding); - }, this); + }, me); } else { } @@ -324,21 +329,22 @@ module.exports = function(Chart) { // Handle an event handleEvent: function(e) { - var position = helpers.getRelativePosition(e, this.chart.chart), + var me = this; + var position = helpers.getRelativePosition(e, me.chart.chart), x = position.x, y = position.y, - opts = this.options; + opts = me.options; - if (x >= this.left && x <= this.right && y >= this.top && y <= this.bottom) { + if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) { // See if we are touching one of the dataset boxes - var lh = this.legendHitBoxes; + var lh = me.legendHitBoxes; for (var i = 0; i < lh.length; ++i) { var hitBox = lh[i]; if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) { // Touching an element if (opts.onClick) { - opts.onClick.call(this, e, this.legendItems[i]); + opts.onClick.call(me, e, me.legendItems[i]); } break; } diff --git a/src/core/core.scale.js b/src/core/core.scale.js index cf6afb0f3..eea019911 100644 --- a/src/core/core.scale.js +++ b/src/core/core.scale.js @@ -59,14 +59,15 @@ module.exports = function(Chart) { helpers.callCallback(this.options.beforeUpdate, [this]); }, update: function(maxWidth, maxHeight, margins) { + var me = this; // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) - this.beforeUpdate(); + me.beforeUpdate(); // Absorb the master measurements - this.maxWidth = maxWidth; - this.maxHeight = maxHeight; - this.margins = helpers.extend({ + me.maxWidth = maxWidth; + me.maxHeight = maxHeight; + me.margins = helpers.extend({ left: 0, right: 0, top: 0, @@ -74,36 +75,36 @@ module.exports = function(Chart) { }, margins); // Dimensions - this.beforeSetDimensions(); - this.setDimensions(); - this.afterSetDimensions(); + me.beforeSetDimensions(); + me.setDimensions(); + me.afterSetDimensions(); // Data min/max - this.beforeDataLimits(); - this.determineDataLimits(); - this.afterDataLimits(); + me.beforeDataLimits(); + me.determineDataLimits(); + me.afterDataLimits(); // Ticks - this.beforeBuildTicks(); - this.buildTicks(); - this.afterBuildTicks(); + me.beforeBuildTicks(); + me.buildTicks(); + me.afterBuildTicks(); - this.beforeTickToLabelConversion(); - this.convertTicksToLabels(); - this.afterTickToLabelConversion(); + me.beforeTickToLabelConversion(); + me.convertTicksToLabels(); + me.afterTickToLabelConversion(); // Tick Rotation - this.beforeCalculateTickRotation(); - this.calculateTickRotation(); - this.afterCalculateTickRotation(); + me.beforeCalculateTickRotation(); + me.calculateTickRotation(); + me.afterCalculateTickRotation(); // Fit - this.beforeFit(); - this.fit(); - this.afterFit(); + me.beforeFit(); + me.fit(); + me.afterFit(); // - this.afterUpdate(); + me.afterUpdate(); - return this.minSize; + return me.minSize; }, afterUpdate: function() { @@ -116,25 +117,26 @@ module.exports = function(Chart) { helpers.callCallback(this.options.beforeSetDimensions, [this]); }, setDimensions: function() { + var me = this; // Set the unconstrained dimension before label rotation - if (this.isHorizontal()) { + if (me.isHorizontal()) { // Reset position before calculating rotation - this.width = this.maxWidth; - this.left = 0; - this.right = this.width; + me.width = me.maxWidth; + me.left = 0; + me.right = me.width; } else { - this.height = this.maxHeight; + me.height = me.maxHeight; // Reset position before calculating rotation - this.top = 0; - this.bottom = this.height; + me.top = 0; + me.bottom = me.height; } // Reset padding - this.paddingLeft = 0; - this.paddingTop = 0; - this.paddingRight = 0; - this.paddingBottom = 0; + me.paddingLeft = 0; + me.paddingTop = 0; + me.paddingRight = 0; + me.paddingBottom = 0; }, afterSetDimensions: function() { helpers.callCallback(this.options.afterSetDimensions, [this]); @@ -162,14 +164,15 @@ module.exports = function(Chart) { helpers.callCallback(this.options.beforeTickToLabelConversion, [this]); }, convertTicksToLabels: function() { + var me = this; // Convert ticks to strings - this.ticks = this.ticks.map(function(numericalTick, index, ticks) { - if (this.options.ticks.userCallback) { - return this.options.ticks.userCallback(numericalTick, index, ticks); + me.ticks = me.ticks.map(function(numericalTick, index, ticks) { + if (me.options.ticks.userCallback) { + return me.options.ticks.userCallback(numericalTick, index, ticks); } - return this.options.ticks.callback(numericalTick, index, ticks); + return me.options.ticks.callback(numericalTick, index, ticks); }, - this); + me); }, afterTickToLabelConversion: function() { helpers.callCallback(this.options.afterTickToLabelConversion, [this]); @@ -181,9 +184,10 @@ module.exports = function(Chart) { helpers.callCallback(this.options.beforeCalculateTickRotation, [this]); }, calculateTickRotation: function() { - var context = this.ctx; + var me = this; + var context = me.ctx; var globalDefaults = Chart.defaults.global; - var optionTicks = this.options.ticks; + var optionTicks = me.options.ticks; //Get the width of each grid by calculating the difference //between x offsets between 0 and 1. @@ -193,60 +197,60 @@ module.exports = function(Chart) { var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); context.font = tickLabelFont; - var firstWidth = context.measureText(this.ticks[0]).width; - var lastWidth = context.measureText(this.ticks[this.ticks.length - 1]).width; + var firstWidth = context.measureText(me.ticks[0]).width; + var lastWidth = context.measureText(me.ticks[me.ticks.length - 1]).width; var firstRotated; - this.labelRotation = optionTicks.minRotation || 0; - this.paddingRight = 0; - this.paddingLeft = 0; + me.labelRotation = optionTicks.minRotation || 0; + me.paddingRight = 0; + me.paddingLeft = 0; - if (this.options.display) { - if (this.isHorizontal()) { - this.paddingRight = lastWidth / 2 + 3; - this.paddingLeft = firstWidth / 2 + 3; + if (me.options.display) { + if (me.isHorizontal()) { + me.paddingRight = lastWidth / 2 + 3; + me.paddingLeft = firstWidth / 2 + 3; - if (!this.longestTextCache) { - this.longestTextCache = {}; + if (!me.longestTextCache) { + me.longestTextCache = {}; } - var originalLabelWidth = helpers.longestText(context, tickLabelFont, this.ticks, this.longestTextCache); + var originalLabelWidth = helpers.longestText(context, tickLabelFont, me.ticks, me.longestTextCache); var labelWidth = originalLabelWidth; var cosRotation; var sinRotation; // Allow 3 pixels x2 padding either side for label readability // only the index matters for a dataset scale, but we want a consistent interface between scales - var tickWidth = this.getPixelForTick(1) - this.getPixelForTick(0) - 6; + var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6; //Max label rotation can be set or default to 90 - also act as a loop counter - while (labelWidth > tickWidth && this.labelRotation < optionTicks.maxRotation) { - cosRotation = Math.cos(helpers.toRadians(this.labelRotation)); - sinRotation = Math.sin(helpers.toRadians(this.labelRotation)); + while (labelWidth > tickWidth && me.labelRotation < optionTicks.maxRotation) { + cosRotation = Math.cos(helpers.toRadians(me.labelRotation)); + sinRotation = Math.sin(helpers.toRadians(me.labelRotation)); firstRotated = cosRotation * firstWidth; // We're right aligning the text now. - if (firstRotated + tickFontSize / 2 > this.yLabelWidth) { - this.paddingLeft = firstRotated + tickFontSize / 2; + if (firstRotated + tickFontSize / 2 > me.yLabelWidth) { + me.paddingLeft = firstRotated + tickFontSize / 2; } - this.paddingRight = tickFontSize / 2; + me.paddingRight = tickFontSize / 2; - if (sinRotation * originalLabelWidth > this.maxHeight) { + if (sinRotation * originalLabelWidth > me.maxHeight) { // go back one step - this.labelRotation--; + me.labelRotation--; break; } - this.labelRotation++; + me.labelRotation++; labelWidth = cosRotation * originalLabelWidth; } } } - if (this.margins) { - this.paddingLeft = Math.max(this.paddingLeft - this.margins.left, 0); - this.paddingRight = Math.max(this.paddingRight - this.margins.right, 0); + if (me.margins) { + me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0); + me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0); } }, afterCalculateTickRotation: function() { @@ -259,18 +263,19 @@ module.exports = function(Chart) { helpers.callCallback(this.options.beforeFit, [this]); }, fit: function() { + var me = this; // Reset - var minSize = this.minSize = { + var minSize = me.minSize = { width: 0, height: 0 }; - var opts = this.options; + var opts = me.options; var globalDefaults = Chart.defaults.global; var tickOpts = opts.ticks; var scaleLabelOpts = opts.scaleLabel; var display = opts.display; - var isHorizontal = this.isHorizontal(); + var isHorizontal = me.isHorizontal(); var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize); var tickFontStyle = helpers.getValueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle); @@ -287,7 +292,7 @@ module.exports = function(Chart) { // Width if (isHorizontal) { // subtract the margins to line up with the chartArea if we are a full width scale - minSize.width = this.isFullWidth() ? this.maxWidth - this.margins.left - this.margins.right : this.maxWidth; + minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth; } else { minSize.width = display ? tickMarkLength : 0; } @@ -296,7 +301,7 @@ module.exports = function(Chart) { if (isHorizontal) { minSize.height = display ? tickMarkLength : 0; } else { - minSize.height = this.maxHeight; // fill all the height + minSize.height = me.maxHeight; // fill all the height } // Are we showing a title for the scale? @@ -310,39 +315,39 @@ module.exports = function(Chart) { if (tickOpts.display && display) { // Don't bother fitting the ticks if we are not showing them - if (!this.longestTextCache) { - this.longestTextCache = {}; + if (!me.longestTextCache) { + me.longestTextCache = {}; } - var largestTextWidth = helpers.longestText(this.ctx, tickLabelFont, this.ticks, this.longestTextCache); + var largestTextWidth = helpers.longestText(me.ctx, tickLabelFont, me.ticks, me.longestTextCache); if (isHorizontal) { // A horizontal axis is more constrained by the height. - this.longestLabelWidth = largestTextWidth; + me.longestLabelWidth = largestTextWidth; // TODO - improve this calculation - var labelHeight = (Math.sin(helpers.toRadians(this.labelRotation)) * this.longestLabelWidth) + 1.5 * tickFontSize; + var labelHeight = (Math.sin(helpers.toRadians(me.labelRotation)) * me.longestLabelWidth) + 1.5 * tickFontSize; - minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight); - this.ctx.font = tickLabelFont; + minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight); + me.ctx.font = tickLabelFont; - var firstLabelWidth = this.ctx.measureText(this.ticks[0]).width; - var lastLabelWidth = this.ctx.measureText(this.ticks[this.ticks.length - 1]).width; + var firstLabelWidth = me.ctx.measureText(me.ticks[0]).width; + var lastLabelWidth = me.ctx.measureText(me.ticks[me.ticks.length - 1]).width; // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned which means that the right padding is dominated // by the font height - var cosRotation = Math.cos(helpers.toRadians(this.labelRotation)); - var sinRotation = Math.sin(helpers.toRadians(this.labelRotation)); - this.paddingLeft = this.labelRotation !== 0 ? (cosRotation * firstLabelWidth) + 3 : firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges - this.paddingRight = this.labelRotation !== 0 ? (sinRotation * (tickFontSize / 2)) + 3 : lastLabelWidth / 2 + 3; // when rotated + var cosRotation = Math.cos(helpers.toRadians(me.labelRotation)); + var sinRotation = Math.sin(helpers.toRadians(me.labelRotation)); + me.paddingLeft = me.labelRotation !== 0 ? (cosRotation * firstLabelWidth) + 3 : firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges + me.paddingRight = me.labelRotation !== 0 ? (sinRotation * (tickFontSize / 2)) + 3 : lastLabelWidth / 2 + 3; // when rotated } else { // A vertical axis is more constrained by the width. Labels are the dominant factor here, so get that length first - var maxLabelWidth = this.maxWidth - minSize.width; + var maxLabelWidth = me.maxWidth - minSize.width; // Account for padding var mirror = tickOpts.mirror; if (!mirror) { - largestTextWidth += this.options.ticks.padding; + largestTextWidth += me.options.ticks.padding; } else { // If mirrored text is on the inside so don't expand largestTextWidth = 0; @@ -353,23 +358,23 @@ module.exports = function(Chart) { minSize.width += largestTextWidth; } else { // Expand to max size - minSize.width = this.maxWidth; + minSize.width = me.maxWidth; } - this.paddingTop = tickFontSize / 2; - this.paddingBottom = tickFontSize / 2; + me.paddingTop = tickFontSize / 2; + me.paddingBottom = tickFontSize / 2; } } - if (this.margins) { - this.paddingLeft = Math.max(this.paddingLeft - this.margins.left, 0); - this.paddingTop = Math.max(this.paddingTop - this.margins.top, 0); - this.paddingRight = Math.max(this.paddingRight - this.margins.right, 0); - this.paddingBottom = Math.max(this.paddingBottom - this.margins.bottom, 0); + if (me.margins) { + me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0); + me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0); + me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0); + me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0); } - this.width = minSize.width; - this.height = minSize.height; + me.width = minSize.width; + me.height = minSize.height; }, afterFit: function() { @@ -419,35 +424,37 @@ module.exports = function(Chart) { // Used for tick location, should getPixelForTick: function(index, includeOffset) { - if (this.isHorizontal()) { - var innerWidth = this.width - (this.paddingLeft + this.paddingRight); - var tickWidth = innerWidth / Math.max((this.ticks.length - ((this.options.gridLines.offsetGridLines) ? 0 : 1)), 1); - var pixel = (tickWidth * index) + this.paddingLeft; + var me = this; + if (me.isHorizontal()) { + var innerWidth = me.width - (me.paddingLeft + me.paddingRight); + var tickWidth = innerWidth / Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); + var pixel = (tickWidth * index) + me.paddingLeft; if (includeOffset) { pixel += tickWidth / 2; } - var finalVal = this.left + Math.round(pixel); - finalVal += this.isFullWidth() ? this.margins.left : 0; + var finalVal = me.left + Math.round(pixel); + finalVal += me.isFullWidth() ? me.margins.left : 0; return finalVal; } else { - var innerHeight = this.height - (this.paddingTop + this.paddingBottom); - return this.top + (index * (innerHeight / (this.ticks.length - 1))); + var innerHeight = me.height - (me.paddingTop + me.paddingBottom); + return me.top + (index * (innerHeight / (me.ticks.length - 1))); } }, // Utility for getting the pixel location of a percentage of scale getPixelForDecimal: function(decimal /*, includeOffset*/ ) { - if (this.isHorizontal()) { - var innerWidth = this.width - (this.paddingLeft + this.paddingRight); - var valueOffset = (innerWidth * decimal) + this.paddingLeft; + var me = this; + if (me.isHorizontal()) { + var innerWidth = me.width - (me.paddingLeft + me.paddingRight); + var valueOffset = (innerWidth * decimal) + me.paddingLeft; - var finalVal = this.left + Math.round(valueOffset); - finalVal += this.isFullWidth() ? this.margins.left : 0; + var finalVal = me.left + Math.round(valueOffset); + finalVal += me.isFullWidth() ? me.margins.left : 0; return finalVal; } else { - return this.top + (decimal * this.height); + return me.top + (decimal * me.height); } }, @@ -466,19 +473,20 @@ module.exports = function(Chart) { // Actualy draw the scale on the canvas // @param {rectangle} chartArea : the area of the chart to draw full grid lines on draw: function(chartArea) { - var options = this.options; + var me = this; + var options = me.options; if (!options.display) { return; } - var context = this.ctx; + var context = me.ctx; var globalDefaults = Chart.defaults.global; var optionTicks = options.ticks; var gridLines = options.gridLines; var scaleLabel = options.scaleLabel; var setContextLineSettings; - var isRotated = this.labelRotation !== 0; + var isRotated = me.labelRotation !== 0; var skipRatio; var scaleLabelX; var scaleLabelY; @@ -503,19 +511,19 @@ module.exports = function(Chart) { var scaleLabelFontFamily = helpers.getValueOrDefault(scaleLabel.fontFamily, globalDefaults.defaultFontFamily); var scaleLabelFont = helpers.fontString(scaleLabelFontSize, scaleLabelFontStyle, scaleLabelFontFamily); - var labelRotationRadians = helpers.toRadians(this.labelRotation); + var labelRotationRadians = helpers.toRadians(me.labelRotation); var cosRotation = Math.cos(labelRotationRadians); var sinRotation = Math.sin(labelRotationRadians); - var longestRotatedLabel = this.longestLabelWidth * cosRotation; + var longestRotatedLabel = me.longestLabelWidth * cosRotation; var rotatedLabelHeight = tickFontSize * sinRotation; // Make sure we draw text in the correct color and font context.fillStyle = tickFontColor; - if (this.isHorizontal()) { + if (me.isHorizontal()) { setContextLineSettings = true; - var yTickStart = options.position === "bottom" ? this.top : this.bottom - tl; - var yTickEnd = options.position === "bottom" ? this.top + tl : this.bottom; + var yTickStart = options.position === "bottom" ? me.top : me.bottom - tl; + var yTickEnd = options.position === "bottom" ? me.top + tl : me.bottom; skipRatio = false; // Only calculate the skip ratio with the half width of longestRotateLabel if we got an actual rotation @@ -524,14 +532,14 @@ module.exports = function(Chart) { longestRotatedLabel /= 2; } - if ((longestRotatedLabel + optionTicks.autoSkipPadding) * this.ticks.length > (this.width - (this.paddingLeft + this.paddingRight))) { - skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * this.ticks.length) / (this.width - (this.paddingLeft + this.paddingRight))); + if ((longestRotatedLabel + optionTicks.autoSkipPadding) * me.ticks.length > (me.width - (me.paddingLeft + me.paddingRight))) { + skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * me.ticks.length) / (me.width - (me.paddingLeft + me.paddingRight))); } // if they defined a max number of optionTicks, // increase skipRatio until that number is met - if (maxTicks && this.ticks.length > maxTicks) { - while (!skipRatio || this.ticks.length / (skipRatio || 1) > maxTicks) { + if (maxTicks && me.ticks.length > maxTicks) { + while (!skipRatio || me.ticks.length / (skipRatio || 1) > maxTicks) { if (!skipRatio) { skipRatio = 1; } @@ -543,20 +551,20 @@ module.exports = function(Chart) { skipRatio = false; } - helpers.each(this.ticks, function (label, index) { + helpers.each(me.ticks, function (label, index) { // Blank optionTicks - var isLastTick = this.ticks.length === index + 1; + var isLastTick = me.ticks.length === index + 1; // Since we always show the last tick,we need may need to hide the last shown one before - var shouldSkip = (skipRatio > 1 && index % skipRatio > 0) || (index % skipRatio === 0 && index + skipRatio >= this.ticks.length); + var shouldSkip = (skipRatio > 1 && index % skipRatio > 0) || (index % skipRatio === 0 && index + skipRatio >= me.ticks.length); if (shouldSkip && !isLastTick || (label === undefined || label === null)) { return; } - var xLineValue = this.getPixelForTick(index); // xvalues for grid lines - var xLabelValue = this.getPixelForTick(index, gridLines.offsetGridLines); // x values for optionTicks (need to consider offsetLabel option) + var xLineValue = me.getPixelForTick(index); // xvalues for grid lines + var xLabelValue = me.getPixelForTick(index, gridLines.offsetGridLines); // x values for optionTicks (need to consider offsetLabel option) if (gridLines.display) { - if (index === (typeof this.zeroLineIndex !== 'undefined' ? this.zeroLineIndex : 0)) { + if (index === (typeof me.zeroLineIndex !== 'undefined' ? me.zeroLineIndex : 0)) { // Draw the first index specially context.lineWidth = gridLines.zeroLineWidth; context.strokeStyle = gridLines.zeroLineColor; @@ -589,7 +597,7 @@ module.exports = function(Chart) { if (optionTicks.display) { context.save(); - context.translate(xLabelValue + optionTicks.labelOffset, (isRotated) ? this.top + 12 : options.position === "top" ? this.bottom - tl : this.top + tl); + context.translate(xLabelValue + optionTicks.labelOffset, (isRotated) ? me.top + 12 : options.position === "top" ? me.bottom - tl : me.top + tl); context.rotate(labelRotationRadians * -1); context.font = tickLabelFont; context.textAlign = (isRotated) ? "right" : "center"; @@ -597,7 +605,7 @@ module.exports = function(Chart) { context.fillText(label, 0, 0); context.restore(); } - }, this); + }, me); if (scaleLabel.display) { // Draw the scale label @@ -606,27 +614,27 @@ module.exports = function(Chart) { context.fillStyle = scaleLabelFontColor; // render in correct colour context.font = scaleLabelFont; - scaleLabelX = this.left + ((this.right - this.left) / 2); // midpoint of the width - scaleLabelY = options.position === 'bottom' ? this.bottom - (scaleLabelFontSize / 2) : this.top + (scaleLabelFontSize / 2); + scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width + scaleLabelY = options.position === 'bottom' ? me.bottom - (scaleLabelFontSize / 2) : me.top + (scaleLabelFontSize / 2); context.fillText(scaleLabel.labelString, scaleLabelX, scaleLabelY); } } else { setContextLineSettings = true; - var xTickStart = options.position === "right" ? this.left : this.right - 5; - var xTickEnd = options.position === "right" ? this.left + 5 : this.right; + var xTickStart = options.position === "right" ? me.left : me.right - 5; + var xTickEnd = options.position === "right" ? me.left + 5 : me.right; - helpers.each(this.ticks, function (label, index) { + helpers.each(me.ticks, function (label, index) { // If the callback returned a null or undefined value, do not draw this line if (label === undefined || label === null) { return; } - var yLineValue = this.getPixelForTick(index); // xvalues for grid lines + var yLineValue = me.getPixelForTick(index); // xvalues for grid lines if (gridLines.display) { - if (index === (typeof this.zeroLineIndex !== 'undefined' ? this.zeroLineIndex : 0)) { + if (index === (typeof me.zeroLineIndex !== 'undefined' ? me.zeroLineIndex : 0)) { // Draw the first index specially context.lineWidth = gridLines.zeroLineWidth; context.strokeStyle = gridLines.zeroLineColor; @@ -659,25 +667,25 @@ module.exports = function(Chart) { if (optionTicks.display) { var xLabelValue; - var yLabelValue = this.getPixelForTick(index, gridLines.offsetGridLines); // x values for optionTicks (need to consider offsetLabel option) + var yLabelValue = me.getPixelForTick(index, gridLines.offsetGridLines); // x values for optionTicks (need to consider offsetLabel option) context.save(); if (options.position === "left") { if (optionTicks.mirror) { - xLabelValue = this.right + optionTicks.padding; + xLabelValue = me.right + optionTicks.padding; context.textAlign = "left"; } else { - xLabelValue = this.right - optionTicks.padding; + xLabelValue = me.right - optionTicks.padding; context.textAlign = "right"; } } else { // right side if (optionTicks.mirror) { - xLabelValue = this.left - optionTicks.padding; + xLabelValue = me.left - optionTicks.padding; context.textAlign = "right"; } else { - xLabelValue = this.left + optionTicks.padding; + xLabelValue = me.left + optionTicks.padding; context.textAlign = "left"; } } @@ -689,12 +697,12 @@ module.exports = function(Chart) { context.fillText(label, 0, 0); context.restore(); } - }, this); + }, me); if (scaleLabel.display) { // Draw the scale label - scaleLabelX = options.position === 'left' ? this.left + (scaleLabelFontSize / 2) : this.right - (scaleLabelFontSize / 2); - scaleLabelY = this.top + ((this.bottom - this.top) / 2); + scaleLabelX = options.position === 'left' ? me.left + (scaleLabelFontSize / 2) : me.right - (scaleLabelFontSize / 2); + scaleLabelY = me.top + ((me.bottom - me.top) / 2); var rotation = options.position === 'left' ? -0.5 * Math.PI : 0.5 * Math.PI; context.save(); @@ -713,18 +721,18 @@ module.exports = function(Chart) { // Draw the line at the edge of the axis context.lineWidth = gridLines.lineWidth; context.strokeStyle = gridLines.color; - var x1 = this.left, - x2 = this.right, - y1 = this.top, - y2 = this.bottom; + var x1 = me.left, + x2 = me.right, + y1 = me.top, + y2 = me.bottom; var aliasPixel = helpers.aliasPixel(context.lineWidth); - if (this.isHorizontal()) { - y1 = y2 = options.position === 'top' ? this.bottom : this.top; + if (me.isHorizontal()) { + y1 = y2 = options.position === 'top' ? me.bottom : me.top; y1 += aliasPixel; y2 += aliasPixel; } else { - x1 = x2 = options.position === 'left' ? this.right : this.left; + x1 = x2 = options.position === 'left' ? me.right : me.left; x1 += aliasPixel; x2 += aliasPixel; } diff --git a/src/core/core.title.js b/src/core/core.title.js index ab969d461..b74f6f829 100644 --- a/src/core/core.title.js +++ b/src/core/core.title.js @@ -20,43 +20,50 @@ module.exports = function(Chart) { Chart.Title = Chart.Element.extend({ initialize: function(config) { - helpers.extend(this, config); - this.options = helpers.configMerge(Chart.defaults.global.title, config.options); + var me = this; + helpers.extend(me, config); + me.options = helpers.configMerge(Chart.defaults.global.title, config.options); // Contains hit boxes for each dataset (in dataset order) - this.legendHitBoxes = []; + me.legendHitBoxes = []; }, // These methods are ordered by lifecyle. Utilities then follow. - beforeUpdate: noop, + beforeUpdate: function () { + var chartOpts = this.chart.options; + if (chartOpts && chartOpts.title) { + this.options = helpers.configMerge(Chart.defaults.global.title, chartOpts.title); + } + }, update: function(maxWidth, maxHeight, margins) { - + var me = this; + // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) - this.beforeUpdate(); + me.beforeUpdate(); // Absorb the master measurements - this.maxWidth = maxWidth; - this.maxHeight = maxHeight; - this.margins = margins; + me.maxWidth = maxWidth; + me.maxHeight = maxHeight; + me.margins = margins; // Dimensions - this.beforeSetDimensions(); - this.setDimensions(); - this.afterSetDimensions(); + me.beforeSetDimensions(); + me.setDimensions(); + me.afterSetDimensions(); // Labels - this.beforeBuildLabels(); - this.buildLabels(); - this.afterBuildLabels(); + me.beforeBuildLabels(); + me.buildLabels(); + me.afterBuildLabels(); // Fit - this.beforeFit(); - this.fit(); - this.afterFit(); + me.beforeFit(); + me.fit(); + me.afterFit(); // - this.afterUpdate(); + me.afterUpdate(); - return this.minSize; + return me.minSize; }, afterUpdate: noop, @@ -65,28 +72,29 @@ module.exports = function(Chart) { beforeSetDimensions: noop, setDimensions: function() { + var me = this; // Set the unconstrained dimension before label rotation - if (this.isHorizontal()) { + if (me.isHorizontal()) { // Reset position before calculating rotation - this.width = this.maxWidth; - this.left = 0; - this.right = this.width; + me.width = me.maxWidth; + me.left = 0; + me.right = me.width; } else { - this.height = this.maxHeight; + me.height = me.maxHeight; // Reset position before calculating rotation - this.top = 0; - this.bottom = this.height; + me.top = 0; + me.bottom = me.height; } // Reset padding - this.paddingLeft = 0; - this.paddingTop = 0; - this.paddingRight = 0; - this.paddingBottom = 0; + me.paddingLeft = 0; + me.paddingTop = 0; + me.paddingRight = 0; + me.paddingBottom = 0; // Reset minSize - this.minSize = { + me.minSize = { width: 0, height: 0 }; @@ -104,25 +112,25 @@ module.exports = function(Chart) { beforeFit: noop, fit: function() { - var _this = this, - ctx = _this.ctx, + var me = this, + ctx = me.ctx, valueOrDefault = helpers.getValueOrDefault, - opts = _this.options, + opts = me.options, globalDefaults = Chart.defaults.global, display = opts.display, fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize), - minSize = _this.minSize; + minSize = me.minSize; - if (_this.isHorizontal()) { - minSize.width = _this.maxWidth; // fill all the width + if (me.isHorizontal()) { + minSize.width = me.maxWidth; // fill all the width minSize.height = display ? fontSize + (opts.padding * 2) : 0; } else { minSize.width = display ? fontSize + (opts.padding * 2) : 0; - minSize.height = _this.maxHeight; // fill all the height + minSize.height = me.maxHeight; // fill all the height } - _this.width = minSize.width; - _this.height = minSize.height; + me.width = minSize.width; + me.height = minSize.height; }, afterFit: noop, @@ -135,10 +143,10 @@ module.exports = function(Chart) { // Actualy draw the title block on the canvas draw: function() { - var _this = this, - ctx = _this.ctx, + var me = this, + ctx = me.ctx, valueOrDefault = helpers.getValueOrDefault, - opts = _this.options, + opts = me.options, globalDefaults = Chart.defaults.global; if (opts.display) { @@ -149,16 +157,16 @@ module.exports = function(Chart) { rotation = 0, titleX, titleY, - top = _this.top, - left = _this.left, - bottom = _this.bottom, - right = _this.right; + top = me.top, + left = me.left, + bottom = me.bottom, + right = me.right; ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour ctx.font = titleFont; // Horizontal - if (_this.isHorizontal()) { + if (me.isHorizontal()) { titleX = left + ((right - left) / 2); // midpoint of the width titleY = top + ((bottom - top) / 2); // midpoint of the height } else { @@ -195,4 +203,4 @@ module.exports = function(Chart) { } } }); -}; \ No newline at end of file +}; diff --git a/src/core/core.tooltip.js b/src/core/core.tooltip.js index e7abf7229..113c94f41 100644 --- a/src/core/core.tooltip.js +++ b/src/core/core.tooltip.js @@ -215,8 +215,7 @@ module.exports = function(Chart) { // Args are: (tooltipItem, data) getBeforeBody: function() { - var me = this; - var lines = me._options.callbacks.beforeBody.apply(me, arguments); + var lines = this._options.callbacks.beforeBody.apply(this, arguments); return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : []; }, @@ -244,8 +243,7 @@ module.exports = function(Chart) { // Args are: (tooltipItem, data) getAfterBody: function() { - var me = this; - var lines = me._options.callbacks.afterBody.apply(me, arguments); + var lines = this._options.callbacks.afterBody.apply(this, arguments); return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : []; }, @@ -330,8 +328,7 @@ module.exports = function(Chart) { return me; }, getTooltipSize: function getTooltipSize(vm) { - var me = this; - var ctx = me._chart.ctx; + var ctx = this._chart.ctx; var size = { height: vm.yPadding * 2, // Tooltip Padding @@ -501,9 +498,8 @@ module.exports = function(Chart) { return pt; }, drawCaret: function drawCaret(tooltipPoint, size, opacity, caretPadding) { - var me = this; - var vm = me._view; - var ctx = me._chart.ctx; + var vm = this._view; + var ctx = this._chart.ctx; var x1, x2, x3; var y1, y2, y3; var caretSize = vm.caretSize; @@ -591,7 +587,6 @@ module.exports = function(Chart) { } }, drawBody: function drawBody(pt, vm, ctx, opacity) { - var me = this; var bodyFontSize = vm.bodyFontSize; var bodySpacing = vm.bodySpacing; var body = vm.body; diff --git a/src/elements/element.line.js b/src/elements/element.line.js index 997dec5e7..47e4a2112 100644 --- a/src/elements/element.line.js +++ b/src/elements/element.line.js @@ -19,12 +19,13 @@ module.exports = function(Chart) { Chart.elements.Line = Chart.Element.extend({ lineToNextPoint: function(previousPoint, point, nextPoint, skipHandler, previousSkipHandler) { - var ctx = this._chart.ctx; + var me = this; + var ctx = me._chart.ctx; if (point._view.skip) { - skipHandler.call(this, previousPoint, point, nextPoint); + skipHandler.call(me, previousPoint, point, nextPoint); } else if (previousPoint._view.skip) { - previousSkipHandler.call(this, previousPoint, point, nextPoint); + previousSkipHandler.call(me, previousPoint, point, nextPoint); } else if (point._view.tension === 0) { ctx.lineTo(point._view.x, point._view.y); } else { @@ -41,12 +42,12 @@ module.exports = function(Chart) { }, draw: function() { - var _this = this; + var me = this; - var vm = this._view; - var ctx = this._chart.ctx; - var first = this._children[0]; - var last = this._children[this._children.length - 1]; + var vm = me._view; + var ctx = me._chart.ctx; + var first = me._children[0]; + var last = me._children[me._children.length - 1]; function loopBackToStart(drawLineToCenter) { if (!first._view.skip && !last._view.skip) { @@ -61,59 +62,59 @@ module.exports = function(Chart) { ); } else if (drawLineToCenter) { // Go to center - ctx.lineTo(_this._view.scaleZero.x, _this._view.scaleZero.y); + ctx.lineTo(me._view.scaleZero.x, me._view.scaleZero.y); } } ctx.save(); // If we had points and want to fill this line, do so. - if (this._children.length > 0 && vm.fill) { + if (me._children.length > 0 && vm.fill) { // Draw the background first (so the border is always on top) ctx.beginPath(); - helpers.each(this._children, function(point, index) { - var previous = helpers.previousItem(this._children, index); - var next = helpers.nextItem(this._children, index); + helpers.each(me._children, function(point, index) { + var previous = helpers.previousItem(me._children, index); + var next = helpers.nextItem(me._children, index); // First point moves to it's starting position no matter what if (index === 0) { - if (this._loop) { + if (me._loop) { ctx.moveTo(vm.scaleZero.x, vm.scaleZero.y); } else { ctx.moveTo(point._view.x, vm.scaleZero); } if (point._view.skip) { - if (!this._loop) { - ctx.moveTo(next._view.x, this._view.scaleZero); + if (!me._loop) { + ctx.moveTo(next._view.x, me._view.scaleZero); } } else { ctx.lineTo(point._view.x, point._view.y); } } else { - this.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) { - if (this._loop) { + me.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) { + if (me._loop) { // Go to center - ctx.lineTo(this._view.scaleZero.x, this._view.scaleZero.y); + ctx.lineTo(me._view.scaleZero.x, me._view.scaleZero.y); } else { - ctx.lineTo(previousPoint._view.x, this._view.scaleZero); - ctx.moveTo(nextPoint._view.x, this._view.scaleZero); + ctx.lineTo(previousPoint._view.x, me._view.scaleZero); + ctx.moveTo(nextPoint._view.x, me._view.scaleZero); } }, function(previousPoint, point) { // If we skipped the last point, draw a line to ourselves so that the fill is nice ctx.lineTo(point._view.x, point._view.y); }); } - }, this); + }, me); // For radial scales, loop back around to the first point - if (this._loop) { + if (me._loop) { loopBackToStart(true); } else { //Round off the line by going to the base of the chart, back to the start, then fill. - ctx.lineTo(this._children[this._children.length - 1]._view.x, vm.scaleZero); - ctx.lineTo(this._children[0]._view.x, vm.scaleZero); + ctx.lineTo(me._children[me._children.length - 1]._view.x, vm.scaleZero); + ctx.lineTo(me._children[0]._view.x, vm.scaleZero); } ctx.fillStyle = vm.backgroundColor || globalDefaults.defaultColor; @@ -136,23 +137,23 @@ module.exports = function(Chart) { ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor; ctx.beginPath(); - helpers.each(this._children, function(point, index) { - var previous = helpers.previousItem(this._children, index); - var next = helpers.nextItem(this._children, index); + helpers.each(me._children, function(point, index) { + var previous = helpers.previousItem(me._children, index); + var next = helpers.nextItem(me._children, index); if (index === 0) { ctx.moveTo(point._view.x, point._view.y); } else { - this.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) { + me.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) { ctx.moveTo(nextPoint._view.x, nextPoint._view.y); }, function(previousPoint, point) { // If we skipped the last point, move up to our point preventing a line from being drawn ctx.moveTo(point._view.x, point._view.y); }); } - }, this); + }, me); - if (this._loop && this._children.length > 0) { + if (me._loop && me._children.length > 0) { loopBackToStart(); } diff --git a/src/scales/scale.category.js b/src/scales/scale.category.js index cca238ed9..efbcbcce6 100644 --- a/src/scales/scale.category.js +++ b/src/scales/scale.category.js @@ -11,29 +11,31 @@ module.exports = function(Chart) { var DatasetScale = Chart.Scale.extend({ // Implement this so that determineDataLimits: function() { - this.minIndex = 0; - this.maxIndex = this.chart.data.labels.length - 1; + var me = this; + me.minIndex = 0; + me.maxIndex = me.chart.data.labels.length - 1; var findIndex; - if (this.options.ticks.min !== undefined) { + if (me.options.ticks.min !== undefined) { // user specified min value - findIndex = helpers.indexOf(this.chart.data.labels, this.options.ticks.min); - this.minIndex = findIndex !== -1 ? findIndex : this.minIndex; + findIndex = helpers.indexOf(me.chart.data.labels, me.options.ticks.min); + me.minIndex = findIndex !== -1 ? findIndex : me.minIndex; } - if (this.options.ticks.max !== undefined) { + if (me.options.ticks.max !== undefined) { // user specified max value - findIndex = helpers.indexOf(this.chart.data.labels, this.options.ticks.max); - this.maxIndex = findIndex !== -1 ? findIndex : this.maxIndex; + findIndex = helpers.indexOf(me.chart.data.labels, me.options.ticks.max); + me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex; } - this.min = this.chart.data.labels[this.minIndex]; - this.max = this.chart.data.labels[this.maxIndex]; + me.min = me.chart.data.labels[me.minIndex]; + me.max = me.chart.data.labels[me.maxIndex]; }, buildTicks: function(index) { + var me = this; // If we are viewing some subset of labels, slice the original array - this.ticks = (this.minIndex === 0 && this.maxIndex === this.chart.data.labels.length - 1) ? this.chart.data.labels : this.chart.data.labels.slice(this.minIndex, this.maxIndex + 1); + me.ticks = (me.minIndex === 0 && me.maxIndex === me.chart.data.labels.length - 1) ? me.chart.data.labels : me.chart.data.labels.slice(me.minIndex, me.maxIndex + 1); }, getLabelForIndex: function(index, datasetIndex) { @@ -42,45 +44,47 @@ module.exports = function(Chart) { // Used to get data value locations. Value can either be an index or a numerical value getPixelForValue: function(value, index, datasetIndex, includeOffset) { + var me = this; // 1 is added because we need the length but we have the indexes - var offsetAmt = Math.max((this.maxIndex + 1 - this.minIndex - ((this.options.gridLines.offsetGridLines) ? 0 : 1)), 1); + var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); - if (this.isHorizontal()) { - var innerWidth = this.width - (this.paddingLeft + this.paddingRight); + if (me.isHorizontal()) { + var innerWidth = me.width - (me.paddingLeft + me.paddingRight); var valueWidth = innerWidth / offsetAmt; - var widthOffset = (valueWidth * (index - this.minIndex)) + this.paddingLeft; + var widthOffset = (valueWidth * (index - me.minIndex)) + me.paddingLeft; - if (this.options.gridLines.offsetGridLines && includeOffset) { + if (me.options.gridLines.offsetGridLines && includeOffset) { widthOffset += (valueWidth / 2); } - return this.left + Math.round(widthOffset); + return me.left + Math.round(widthOffset); } else { - var innerHeight = this.height - (this.paddingTop + this.paddingBottom); + var innerHeight = me.height - (me.paddingTop + me.paddingBottom); var valueHeight = innerHeight / offsetAmt; - var heightOffset = (valueHeight * (index - this.minIndex)) + this.paddingTop; + var heightOffset = (valueHeight * (index - me.minIndex)) + me.paddingTop; - if (this.options.gridLines.offsetGridLines && includeOffset) { + if (me.options.gridLines.offsetGridLines && includeOffset) { heightOffset += (valueHeight / 2); } - return this.top + Math.round(heightOffset); + return me.top + Math.round(heightOffset); } }, getPixelForTick: function(index, includeOffset) { return this.getPixelForValue(this.ticks[index], index + this.minIndex, null, includeOffset); }, getValueForPixel: function(pixel) { - var value -; var offsetAmt = Math.max((this.ticks.length - ((this.options.gridLines.offsetGridLines) ? 0 : 1)), 1); - var horz = this.isHorizontal(); - var innerDimension = horz ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom); + var me = this; + var value; + var offsetAmt = Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); + var horz = me.isHorizontal(); + var innerDimension = horz ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom); var valueDimension = innerDimension / offsetAmt; - if (this.options.gridLines.offsetGridLines) { + if (me.options.gridLines.offsetGridLines) { pixel -= (valueDimension / 2); } - pixel -= horz ? this.paddingLeft : this.paddingTop; + pixel -= horz ? me.paddingLeft : me.paddingTop; if (pixel <= 0) { value = 0; diff --git a/src/scales/scale.linear.js b/src/scales/scale.linear.js index c8905769b..31630c284 100644 --- a/src/scales/scale.linear.js +++ b/src/scales/scale.linear.js @@ -37,21 +37,21 @@ module.exports = function(Chart) { var LinearScale = Chart.LinearScaleBase.extend({ determineDataLimits: function() { - var _this = this; - var opts = _this.options; + var me = this; + var opts = me.options; var tickOpts = opts.ticks; - var chart = _this.chart; + var chart = me.chart; var data = chart.data; var datasets = data.datasets; - var isHorizontal = _this.isHorizontal(); + var isHorizontal = me.isHorizontal(); function IDMatches(meta) { - return isHorizontal ? meta.xAxisID === _this.id : meta.yAxisID === _this.id; + return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; } // First Calculate the range - _this.min = null; - _this.max = null; + me.min = null; + me.max = null; if (opts.stacked) { var valuesPerType = {}; @@ -73,7 +73,7 @@ module.exports = function(Chart) { if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { helpers.each(dataset.data, function(rawValue, index) { - var value = +_this.getRightValue(rawValue); + var value = +me.getRightValue(rawValue); if (isNaN(value) || meta.data[index].hidden) { return; } @@ -100,8 +100,8 @@ module.exports = function(Chart) { var values = valuesForType.positiveValues.concat(valuesForType.negativeValues); var minVal = helpers.min(values); var maxVal = helpers.max(values); - _this.min = _this.min === null ? minVal : Math.min(_this.min, minVal); - _this.max = _this.max === null ? maxVal : Math.max(_this.max, maxVal); + me.min = me.min === null ? minVal : Math.min(me.min, minVal); + me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); }); } else { @@ -109,21 +109,21 @@ module.exports = function(Chart) { var meta = chart.getDatasetMeta(datasetIndex); if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { helpers.each(dataset.data, function(rawValue, index) { - var value = +_this.getRightValue(rawValue); + var value = +me.getRightValue(rawValue); if (isNaN(value) || meta.data[index].hidden) { return; } - if (_this.min === null) { - _this.min = value; - } else if (value < _this.min) { - _this.min = value; + if (me.min === null) { + me.min = value; + } else if (value < me.min) { + me.min = value; } - if (_this.max === null) { - _this.max = value; - } else if (value > _this.max) { - _this.max = value; + if (me.max === null) { + me.max = value; + } else if (value > me.max) { + me.max = value; } }); } @@ -150,10 +150,9 @@ module.exports = function(Chart) { }, // Called after the ticks are built. We need handleDirectionalChanges: function() { - var me = this; - if (!me.isHorizontal()) { + if (!this.isHorizontal()) { // We are in a vertical orientation. The top value is the highest. So reverse the array - me.ticks.reverse(); + this.ticks.reverse(); } }, getLabelForIndex: function(index, datasetIndex) { @@ -163,34 +162,34 @@ module.exports = function(Chart) { getPixelForValue: function(value, index, datasetIndex, includeOffset) { // This must be called after fit has been run so that // this.left, this.top, this.right, and this.bottom have been defined - var _this = this; - var paddingLeft = _this.paddingLeft; - var paddingBottom = _this.paddingBottom; - var start = _this.start; + var me = this; + var paddingLeft = me.paddingLeft; + var paddingBottom = me.paddingBottom; + var start = me.start; - var rightValue = +_this.getRightValue(value); + var rightValue = +me.getRightValue(value); var pixel; var innerDimension; - var range = _this.end - start; + var range = me.end - start; - if (_this.isHorizontal()) { - innerDimension = _this.width - (paddingLeft + _this.paddingRight); - pixel = _this.left + (innerDimension / range * (rightValue - start)); + if (me.isHorizontal()) { + innerDimension = me.width - (paddingLeft + me.paddingRight); + pixel = me.left + (innerDimension / range * (rightValue - start)); return Math.round(pixel + paddingLeft); } else { - innerDimension = _this.height - (_this.paddingTop + paddingBottom); - pixel = (_this.bottom - paddingBottom) - (innerDimension / range * (rightValue - start)); + innerDimension = me.height - (me.paddingTop + paddingBottom); + pixel = (me.bottom - paddingBottom) - (innerDimension / range * (rightValue - start)); return Math.round(pixel); } }, getValueForPixel: function(pixel) { - var _this = this; - var isHorizontal = _this.isHorizontal(); - var paddingLeft = _this.paddingLeft; - var paddingBottom = _this.paddingBottom; - var innerDimension = isHorizontal ? _this.width - (paddingLeft + _this.paddingRight) : _this.height - (_this.paddingTop + paddingBottom); - var offset = (isHorizontal ? pixel - _this.left - paddingLeft : _this.bottom - paddingBottom - pixel) / innerDimension; - return _this.start + ((_this.end - _this.start) * offset); + var me = this; + var isHorizontal = me.isHorizontal(); + var paddingLeft = me.paddingLeft; + var paddingBottom = me.paddingBottom; + var innerDimension = isHorizontal ? me.width - (paddingLeft + me.paddingRight) : me.height - (me.paddingTop + paddingBottom); + var offset = (isHorizontal ? pixel - me.left - paddingLeft : me.bottom - paddingBottom - pixel) / innerDimension; + return me.start + ((me.end - me.start) * offset); }, getPixelForTick: function(index, includeOffset) { return this.getPixelForValue(this.ticksAsNumbers[index], null, null, includeOffset); diff --git a/src/scales/scale.linearbase.js b/src/scales/scale.linearbase.js index d127c88f8..45292b812 100644 --- a/src/scales/scale.linearbase.js +++ b/src/scales/scale.linearbase.js @@ -7,43 +7,43 @@ module.exports = function(Chart) { Chart.LinearScaleBase = Chart.Scale.extend({ handleTickRangeOptions: function() { - var _this = this; - var opts = _this.options; + var me = this; + var opts = me.options; var tickOpts = opts.ticks; // If we are forcing it to begin at 0, but 0 will already be rendered on the chart, // do nothing since that would make the chart weird. If the user really wants a weird chart // axis, they can manually override it if (tickOpts.beginAtZero) { - var minSign = helpers.sign(_this.min); - var maxSign = helpers.sign(_this.max); + var minSign = helpers.sign(me.min); + var maxSign = helpers.sign(me.max); if (minSign < 0 && maxSign < 0) { // move the top up to 0 - _this.max = 0; + me.max = 0; } else if (minSign > 0 && maxSign > 0) { // move the botttom down to 0 - _this.min = 0; + me.min = 0; } } if (tickOpts.min !== undefined) { - _this.min = tickOpts.min; + me.min = tickOpts.min; } else if (tickOpts.suggestedMin !== undefined) { - _this.min = Math.min(_this.min, tickOpts.suggestedMin); + me.min = Math.min(me.min, tickOpts.suggestedMin); } if (tickOpts.max !== undefined) { - _this.max = tickOpts.max; + me.max = tickOpts.max; } else if (tickOpts.suggestedMax !== undefined) { - _this.max = Math.max(_this.max, tickOpts.suggestedMax); + me.max = Math.max(me.max, tickOpts.suggestedMax); } - if (_this.min === _this.max) { - _this.max++; + if (me.min === me.max) { + me.max++; if (!tickOpts.beginAtZero) { - _this.min--; + me.min--; } } }, @@ -51,20 +51,20 @@ module.exports = function(Chart) { handleDirectionalChanges: noop, buildTicks: function() { - var _this = this; - var opts = _this.options; + var me = this; + var opts = me.options; var tickOpts = opts.ticks; var getValueOrDefault = helpers.getValueOrDefault; - var isHorizontal = _this.isHorizontal(); + var isHorizontal = me.isHorizontal(); - var ticks = _this.ticks = []; + var ticks = me.ticks = []; // Figure out what the max number of ticks we can support it is based on the size of // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on // the graph - var maxTicks = this.getTickLimit(); + var maxTicks = me.getTickLimit(); // Make sure we always have at least 2 ticks maxTicks = Math.max(2, maxTicks); @@ -78,11 +78,11 @@ module.exports = function(Chart) { if (fixedStepSizeSet) { spacing = getValueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize); } else { - var niceRange = helpers.niceNum(_this.max - _this.min, false); + var niceRange = helpers.niceNum(me.max - me.min, false); spacing = helpers.niceNum(niceRange / (maxTicks - 1), true); } - var niceMin = Math.floor(_this.min / spacing) * spacing; - var niceMax = Math.ceil(_this.max / spacing) * spacing; + var niceMin = Math.floor(me.min / spacing) * spacing; + var niceMax = Math.ceil(me.max / spacing) * spacing; var numSpaces = (niceMax - niceMin) / spacing; // If very close to our rounded value, use it. @@ -99,29 +99,29 @@ module.exports = function(Chart) { } ticks.push(tickOpts.max !== undefined ? tickOpts.max : niceMax); - this.handleDirectionalChanges(); + me.handleDirectionalChanges(); // At this point, we need to update our max and min given the tick values since we have expanded the // range of the scale - _this.max = helpers.max(ticks); - _this.min = helpers.min(ticks); + me.max = helpers.max(ticks); + me.min = helpers.min(ticks); if (tickOpts.reverse) { ticks.reverse(); - _this.start = _this.max; - _this.end = _this.min; + me.start = me.max; + me.end = me.min; } else { - _this.start = _this.min; - _this.end = _this.max; + me.start = me.min; + me.end = me.max; } }, convertTicksToLabels: function() { - var _this = this; - _this.ticksAsNumbers = _this.ticks.slice(); - _this.zeroLineIndex = _this.ticks.indexOf(0); + var me = this; + me.ticksAsNumbers = me.ticks.slice(); + me.zeroLineIndex = me.ticks.indexOf(0); - Chart.Scale.prototype.convertTicksToLabels.call(_this); + Chart.Scale.prototype.convertTicksToLabels.call(me); }, }); }; \ No newline at end of file diff --git a/src/scales/scale.logarithmic.js b/src/scales/scale.logarithmic.js index 4cdc0ac36..3d5bddc3b 100644 --- a/src/scales/scale.logarithmic.js +++ b/src/scales/scale.logarithmic.js @@ -23,21 +23,21 @@ module.exports = function(Chart) { var LogarithmicScale = Chart.Scale.extend({ determineDataLimits: function() { - var _this = this; - var opts = _this.options; + var me = this; + var opts = me.options; var tickOpts = opts.ticks; - var chart = _this.chart; + var chart = me.chart; var data = chart.data; var datasets = data.datasets; var getValueOrDefault = helpers.getValueOrDefault; - var isHorizontal = _this.isHorizontal(); + var isHorizontal = me.isHorizontal(); function IDMatches(meta) { - return isHorizontal ? meta.xAxisID === _this.id : meta.yAxisID === _this.id; + return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; } // Calculate Range - _this.min = null; - _this.max = null; + me.min = null; + me.max = null; if (opts.stacked) { var valuesPerType = {}; @@ -51,7 +51,7 @@ module.exports = function(Chart) { helpers.each(dataset.data, function(rawValue, index) { var values = valuesPerType[meta.type]; - var value = +_this.getRightValue(rawValue); + var value = +me.getRightValue(rawValue); if (isNaN(value) || meta.data[index].hidden) { return; } @@ -71,8 +71,8 @@ module.exports = function(Chart) { helpers.each(valuesPerType, function(valuesForType) { var minVal = helpers.min(valuesForType); var maxVal = helpers.max(valuesForType); - _this.min = _this.min === null ? minVal : Math.min(_this.min, minVal); - _this.max = _this.max === null ? maxVal : Math.max(_this.max, maxVal); + me.min = me.min === null ? minVal : Math.min(me.min, minVal); + me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); }); } else { @@ -80,58 +80,58 @@ module.exports = function(Chart) { var meta = chart.getDatasetMeta(datasetIndex); if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { helpers.each(dataset.data, function(rawValue, index) { - var value = +_this.getRightValue(rawValue); + var value = +me.getRightValue(rawValue); if (isNaN(value) || meta.data[index].hidden) { return; } - if (_this.min === null) { - _this.min = value; - } else if (value < _this.min) { - _this.min = value; + if (me.min === null) { + me.min = value; + } else if (value < me.min) { + me.min = value; } - if (_this.max === null) { - _this.max = value; - } else if (value > _this.max) { - _this.max = value; + if (me.max === null) { + me.max = value; + } else if (value > me.max) { + me.max = value; } }); } }); } - _this.min = getValueOrDefault(tickOpts.min, _this.min); - _this.max = getValueOrDefault(tickOpts.max, _this.max); + me.min = getValueOrDefault(tickOpts.min, me.min); + me.max = getValueOrDefault(tickOpts.max, me.max); - if (_this.min === _this.max) { - if (_this.min !== 0 && _this.min !== null) { - _this.min = Math.pow(10, Math.floor(helpers.log10(_this.min)) - 1); - _this.max = Math.pow(10, Math.floor(helpers.log10(_this.max)) + 1); + if (me.min === me.max) { + if (me.min !== 0 && me.min !== null) { + me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1); + me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1); } else { - _this.min = 1; - _this.max = 10; + me.min = 1; + me.max = 10; } } }, buildTicks: function() { - var _this = this; - var opts = _this.options; + var me = this; + var opts = me.options; var tickOpts = opts.ticks; var getValueOrDefault = helpers.getValueOrDefault; // Reset the ticks array. Later on, we will draw a grid line at these positions // The array simply contains the numerical value of the spots where ticks will be - var ticks = _this.ticks = []; + var ticks = me.ticks = []; // Figure out what the max number of ticks we can support it is based on the size of // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on // the graph - var tickVal = getValueOrDefault(tickOpts.min, Math.pow(10, Math.floor(helpers.log10(_this.min)))); + var tickVal = getValueOrDefault(tickOpts.min, Math.pow(10, Math.floor(helpers.log10(me.min)))); - while (tickVal < _this.max) { + while (tickVal < me.max) { ticks.push(tickVal); var exp = Math.floor(helpers.log10(tickVal)); @@ -148,24 +148,24 @@ module.exports = function(Chart) { var lastTick = getValueOrDefault(tickOpts.max, tickVal); ticks.push(lastTick); - if (!_this.isHorizontal()) { + if (!me.isHorizontal()) { // We are in a vertical orientation. The top value is the highest. So reverse the array ticks.reverse(); } // At this point, we need to update our max and min given the tick values since we have expanded the // range of the scale - _this.max = helpers.max(ticks); - _this.min = helpers.min(ticks); + me.max = helpers.max(ticks); + me.min = helpers.min(ticks); if (tickOpts.reverse) { ticks.reverse(); - _this.start = _this.max; - _this.end = _this.min; + me.start = me.max; + me.end = me.min; } else { - _this.start = _this.min; - _this.end = _this.max; + me.start = me.min; + me.end = me.max; } }, convertTicksToLabels: function() { @@ -181,51 +181,51 @@ module.exports = function(Chart) { return this.getPixelForValue(this.tickValues[index], null, null, includeOffset); }, getPixelForValue: function(value, index, datasetIndex, includeOffset) { - var _this = this; + var me = this; var innerDimension; var pixel; - var start = _this.start; - var newVal = +_this.getRightValue(value); - var range = helpers.log10(_this.end) - helpers.log10(start); - var paddingTop = _this.paddingTop; - var paddingBottom = _this.paddingBottom; - var paddingLeft = _this.paddingLeft; + var start = me.start; + var newVal = +me.getRightValue(value); + var range = helpers.log10(me.end) - helpers.log10(start); + var paddingTop = me.paddingTop; + var paddingBottom = me.paddingBottom; + var paddingLeft = me.paddingLeft; - if (_this.isHorizontal()) { + if (me.isHorizontal()) { if (newVal === 0) { - pixel = _this.left + paddingLeft; + pixel = me.left + paddingLeft; } else { - innerDimension = _this.width - (paddingLeft + _this.paddingRight); - pixel = _this.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); + innerDimension = me.width - (paddingLeft + me.paddingRight); + pixel = me.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); pixel += paddingLeft; } } else { // Bottom - top since pixels increase downard on a screen if (newVal === 0) { - pixel = _this.top + paddingTop; + pixel = me.top + paddingTop; } else { - innerDimension = _this.height - (paddingTop + paddingBottom); - pixel = (_this.bottom - paddingBottom) - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); + innerDimension = me.height - (paddingTop + paddingBottom); + pixel = (me.bottom - paddingBottom) - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); } } return pixel; }, getValueForPixel: function(pixel) { - var _this = this; + var me = this; var offset; - var range = helpers.log10(_this.end) - helpers.log10(_this.start); + var range = helpers.log10(me.end) - helpers.log10(me.start); var value; var innerDimension; - if (_this.isHorizontal()) { - innerDimension = _this.width - (_this.paddingLeft + _this.paddingRight); - value = _this.start * Math.pow(10, (pixel - _this.left - _this.paddingLeft) * range / innerDimension); + if (me.isHorizontal()) { + innerDimension = me.width - (me.paddingLeft + me.paddingRight); + value = me.start * Math.pow(10, (pixel - me.left - me.paddingLeft) * range / innerDimension); } else { - innerDimension = _this.height - (_this.paddingTop + _this.paddingBottom); - value = Math.pow(10, (_this.bottom - _this.paddingBottom - pixel) * range / innerDimension) / _this.start; + innerDimension = me.height - (me.paddingTop + me.paddingBottom); + value = Math.pow(10, (me.bottom - me.paddingBottom - pixel) * range / innerDimension) / me.start; } return value; diff --git a/src/scales/scale.radialLinear.js b/src/scales/scale.radialLinear.js index 3cb238493..de686eedd 100644 --- a/src/scales/scale.radialLinear.js +++ b/src/scales/scale.radialLinear.js @@ -99,10 +99,9 @@ module.exports = function(Chart) { me.handleTickRangeOptions(); }, getTickLimit: function() { - var me = this; - var tickOpts = me.options.ticks; + var tickOpts = this.options.ticks; var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize); - return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.drawingArea / (1.5 * tickFontSize))); + return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize))); }, convertTicksToLabels: function() { var me = this; diff --git a/src/scales/scale.time.js b/src/scales/scale.time.js index 19079f0a5..1c2ef44b9 100644 --- a/src/scales/scale.time.js +++ b/src/scales/scale.time.js @@ -79,114 +79,117 @@ module.exports = function(Chart) { return this.labelMoments[datasetIndex][index]; }, getMomentStartOf: function(tick) { - if (this.options.time.unit === 'week' && this.options.time.isoWeekday !== false) { - return tick.clone().startOf('isoWeek').isoWeekday(this.options.time.isoWeekday); + var me = this; + if (me.options.time.unit === 'week' && me.options.time.isoWeekday !== false) { + return tick.clone().startOf('isoWeek').isoWeekday(me.options.time.isoWeekday); } else { - return tick.clone().startOf(this.tickUnit); + return tick.clone().startOf(me.tickUnit); } }, determineDataLimits: function() { - this.labelMoments = []; + var me = this; + me.labelMoments = []; // Only parse these once. If the dataset does not have data as x,y pairs, we will use // these var scaleLabelMoments = []; - if (this.chart.data.labels && this.chart.data.labels.length > 0) { - helpers.each(this.chart.data.labels, function(label, index) { - var labelMoment = this.parseTime(label); + if (me.chart.data.labels && me.chart.data.labels.length > 0) { + helpers.each(me.chart.data.labels, function(label, index) { + var labelMoment = me.parseTime(label); if (labelMoment.isValid()) { - if (this.options.time.round) { - labelMoment.startOf(this.options.time.round); + if (me.options.time.round) { + labelMoment.startOf(me.options.time.round); } scaleLabelMoments.push(labelMoment); } - }, this); + }, me); - this.firstTick = moment.min.call(this, scaleLabelMoments); - this.lastTick = moment.max.call(this, scaleLabelMoments); + me.firstTick = moment.min.call(me, scaleLabelMoments); + me.lastTick = moment.max.call(me, scaleLabelMoments); } else { - this.firstTick = null; - this.lastTick = null; + me.firstTick = null; + me.lastTick = null; } - helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { + helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) { var momentsForDataset = []; - var datasetVisible = this.chart.isDatasetVisible(datasetIndex); + var datasetVisible = me.chart.isDatasetVisible(datasetIndex); if (typeof dataset.data[0] === 'object' && dataset.data[0] !== null) { helpers.each(dataset.data, function(value, index) { - var labelMoment = this.parseTime(this.getRightValue(value)); + var labelMoment = me.parseTime(me.getRightValue(value)); if (labelMoment.isValid()) { - if (this.options.time.round) { - labelMoment.startOf(this.options.time.round); + if (me.options.time.round) { + labelMoment.startOf(me.options.time.round); } momentsForDataset.push(labelMoment); if (datasetVisible) { // May have gone outside the scale ranges, make sure we keep the first and last ticks updated - this.firstTick = this.firstTick !== null ? moment.min(this.firstTick, labelMoment) : labelMoment; - this.lastTick = this.lastTick !== null ? moment.max(this.lastTick, labelMoment) : labelMoment; + me.firstTick = me.firstTick !== null ? moment.min(me.firstTick, labelMoment) : labelMoment; + me.lastTick = me.lastTick !== null ? moment.max(me.lastTick, labelMoment) : labelMoment; } } - }, this); + }, me); } else { // We have no labels. Use the ones from the scale momentsForDataset = scaleLabelMoments; } - this.labelMoments.push(momentsForDataset); - }, this); + me.labelMoments.push(momentsForDataset); + }, me); // Set these after we've done all the data - if (this.options.time.min) { - this.firstTick = this.parseTime(this.options.time.min); + if (me.options.time.min) { + me.firstTick = me.parseTime(me.options.time.min); } - if (this.options.time.max) { - this.lastTick = this.parseTime(this.options.time.max); + if (me.options.time.max) { + me.lastTick = me.parseTime(me.options.time.max); } // We will modify these, so clone for later - this.firstTick = (this.firstTick || moment()).clone(); - this.lastTick = (this.lastTick || moment()).clone(); + me.firstTick = (me.firstTick || moment()).clone(); + me.lastTick = (me.lastTick || moment()).clone(); }, buildTicks: function(index) { + var me = this; - this.ctx.save(); - var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); - var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); - var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); + me.ctx.save(); + var tickFontSize = helpers.getValueOrDefault(me.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); + var tickFontStyle = helpers.getValueOrDefault(me.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); + var tickFontFamily = helpers.getValueOrDefault(me.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); - this.ctx.font = tickLabelFont; + me.ctx.font = tickLabelFont; - this.ticks = []; - this.unitScale = 1; // How much we scale the unit by, ie 2 means 2x unit per step - this.scaleSizeInUnits = 0; // How large the scale is in the base unit (seconds, minutes, etc) + me.ticks = []; + me.unitScale = 1; // How much we scale the unit by, ie 2 means 2x unit per step + me.scaleSizeInUnits = 0; // How large the scale is in the base unit (seconds, minutes, etc) // Set unit override if applicable - if (this.options.time.unit) { - this.tickUnit = this.options.time.unit || 'day'; - this.displayFormat = this.options.time.displayFormats[this.tickUnit]; - this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true); - this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, 1); + if (me.options.time.unit) { + me.tickUnit = me.options.time.unit || 'day'; + me.displayFormat = me.options.time.displayFormats[me.tickUnit]; + me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true); + me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, 1); } else { // Determine the smallest needed unit of the time - var innerWidth = this.isHorizontal() ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom); + var innerWidth = me.isHorizontal() ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom); // Crude approximation of what the label length might be - var tempFirstLabel = this.tickFormatFunction(this.firstTick, 0, []); - var tickLabelWidth = this.ctx.measureText(tempFirstLabel).width; - var cosRotation = Math.cos(helpers.toRadians(this.options.ticks.maxRotation)); - var sinRotation = Math.sin(helpers.toRadians(this.options.ticks.maxRotation)); + var tempFirstLabel = me.tickFormatFunction(me.firstTick, 0, []); + var tickLabelWidth = me.ctx.measureText(tempFirstLabel).width; + var cosRotation = Math.cos(helpers.toRadians(me.options.ticks.maxRotation)); + var sinRotation = Math.sin(helpers.toRadians(me.options.ticks.maxRotation)); tickLabelWidth = (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation); var labelCapacity = innerWidth / (tickLabelWidth); // Start as small as possible - this.tickUnit = 'millisecond'; - this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true); - this.displayFormat = this.options.time.displayFormats[this.tickUnit]; + me.tickUnit = 'millisecond'; + me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true); + me.displayFormat = me.options.time.displayFormats[me.tickUnit]; var unitDefinitionIndex = 0; var unitDefinition = time.units[unitDefinitionIndex]; @@ -194,32 +197,32 @@ module.exports = function(Chart) { // While we aren't ideal and we don't have units left while (unitDefinitionIndex < time.units.length) { // Can we scale this unit. If `false` we can scale infinitely - this.unitScale = 1; + me.unitScale = 1; - if (helpers.isArray(unitDefinition.steps) && Math.ceil(this.scaleSizeInUnits / labelCapacity) < helpers.max(unitDefinition.steps)) { + if (helpers.isArray(unitDefinition.steps) && Math.ceil(me.scaleSizeInUnits / labelCapacity) < helpers.max(unitDefinition.steps)) { // Use one of the prefedined steps for (var idx = 0; idx < unitDefinition.steps.length; ++idx) { - if (unitDefinition.steps[idx] >= Math.ceil(this.scaleSizeInUnits / labelCapacity)) { - this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, unitDefinition.steps[idx]); + if (unitDefinition.steps[idx] >= Math.ceil(me.scaleSizeInUnits / labelCapacity)) { + me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, unitDefinition.steps[idx]); break; } } break; - } else if ((unitDefinition.maxStep === false) || (Math.ceil(this.scaleSizeInUnits / labelCapacity) < unitDefinition.maxStep)) { + } else if ((unitDefinition.maxStep === false) || (Math.ceil(me.scaleSizeInUnits / labelCapacity) < unitDefinition.maxStep)) { // We have a max step. Scale this unit - this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, Math.ceil(this.scaleSizeInUnits / labelCapacity)); + me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, Math.ceil(me.scaleSizeInUnits / labelCapacity)); break; } else { // Move to the next unit up ++unitDefinitionIndex; unitDefinition = time.units[unitDefinitionIndex]; - this.tickUnit = unitDefinition.name; - var leadingUnitBuffer = this.firstTick.diff(this.getMomentStartOf(this.firstTick), this.tickUnit, true); - var trailingUnitBuffer = this.getMomentStartOf(this.lastTick.clone().add(1, this.tickUnit)).diff(this.lastTick, this.tickUnit, true); - this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true) + leadingUnitBuffer + trailingUnitBuffer; - this.displayFormat = this.options.time.displayFormats[unitDefinition.name]; + me.tickUnit = unitDefinition.name; + var leadingUnitBuffer = me.firstTick.diff(me.getMomentStartOf(me.firstTick), me.tickUnit, true); + var trailingUnitBuffer = me.getMomentStartOf(me.lastTick.clone().add(1, me.tickUnit)).diff(me.lastTick, me.tickUnit, true); + me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true) + leadingUnitBuffer + trailingUnitBuffer; + me.displayFormat = me.options.time.displayFormats[unitDefinition.name]; } } } @@ -227,79 +230,80 @@ module.exports = function(Chart) { var roundedStart; // Only round the first tick if we have no hard minimum - if (!this.options.time.min) { - this.firstTick = this.getMomentStartOf(this.firstTick); - roundedStart = this.firstTick; + if (!me.options.time.min) { + me.firstTick = me.getMomentStartOf(me.firstTick); + roundedStart = me.firstTick; } else { - roundedStart = this.getMomentStartOf(this.firstTick); + roundedStart = me.getMomentStartOf(me.firstTick); } // Only round the last tick if we have no hard maximum - if (!this.options.time.max) { - var roundedEnd = this.getMomentStartOf(this.lastTick); - if (roundedEnd.diff(this.lastTick, this.tickUnit, true) !== 0) { - // Do not use end of because we need this to be in the next time unit - this.lastTick = this.getMomentStartOf(this.lastTick.add(1, this.tickUnit)); + if (!me.options.time.max) { + var roundedEnd = me.getMomentStartOf(me.lastTick); + if (roundedEnd.diff(me.lastTick, me.tickUnit, true) !== 0) { + // Do not use end of because we need me to be in the next time unit + me.lastTick = me.getMomentStartOf(me.lastTick.add(1, me.tickUnit)); } } - this.smallestLabelSeparation = this.width; + me.smallestLabelSeparation = me.width; - helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { - for (var i = 1; i < this.labelMoments[datasetIndex].length; i++) { - this.smallestLabelSeparation = Math.min(this.smallestLabelSeparation, this.labelMoments[datasetIndex][i].diff(this.labelMoments[datasetIndex][i - 1], this.tickUnit, true)); + helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) { + for (var i = 1; i < me.labelMoments[datasetIndex].length; i++) { + me.smallestLabelSeparation = Math.min(me.smallestLabelSeparation, me.labelMoments[datasetIndex][i].diff(me.labelMoments[datasetIndex][i - 1], me.tickUnit, true)); } - }, this); + }, me); // Tick displayFormat override - if (this.options.time.displayFormat) { - this.displayFormat = this.options.time.displayFormat; + if (me.options.time.displayFormat) { + me.displayFormat = me.options.time.displayFormat; } // first tick. will have been rounded correctly if options.time.min is not specified - this.ticks.push(this.firstTick.clone()); + me.ticks.push(me.firstTick.clone()); // For every unit in between the first and last moment, create a moment and add it to the ticks tick - for (var i = 1; i <= this.scaleSizeInUnits; ++i) { - var newTick = roundedStart.clone().add(i, this.tickUnit); + for (var i = 1; i <= me.scaleSizeInUnits; ++i) { + var newTick = roundedStart.clone().add(i, me.tickUnit); // Are we greater than the max time - if (this.options.time.max && newTick.diff(this.lastTick, this.tickUnit, true) >= 0) { + if (me.options.time.max && newTick.diff(me.lastTick, me.tickUnit, true) >= 0) { break; } - if (i % this.unitScale === 0) { - this.ticks.push(newTick); + if (i % me.unitScale === 0) { + me.ticks.push(newTick); } } // Always show the right tick - var diff = this.ticks[this.ticks.length - 1].diff(this.lastTick, this.tickUnit); - if (diff !== 0 || this.scaleSizeInUnits === 0) { + var diff = me.ticks[me.ticks.length - 1].diff(me.lastTick, me.tickUnit); + if (diff !== 0 || me.scaleSizeInUnits === 0) { // this is a weird case. If the option is the same as the end option, we can't just diff the times because the tick was created from the roundedStart // but the last tick was not rounded. - if (this.options.time.max) { - this.ticks.push(this.lastTick.clone()); - this.scaleSizeInUnits = this.lastTick.diff(this.ticks[0], this.tickUnit, true); + if (me.options.time.max) { + me.ticks.push(me.lastTick.clone()); + me.scaleSizeInUnits = me.lastTick.diff(me.ticks[0], me.tickUnit, true); } else { - this.ticks.push(this.lastTick.clone()); - this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true); + me.ticks.push(me.lastTick.clone()); + me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true); } } - this.ctx.restore(); + me.ctx.restore(); }, // Get tooltip label getLabelForIndex: function(index, datasetIndex) { - var label = this.chart.data.labels && index < this.chart.data.labels.length ? this.chart.data.labels[index] : ''; + var me = this; + var label = me.chart.data.labels && index < me.chart.data.labels.length ? me.chart.data.labels[index] : ''; - if (typeof this.chart.data.datasets[datasetIndex].data[0] === 'object') { - label = this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); + if (typeof me.chart.data.datasets[datasetIndex].data[0] === 'object') { + label = me.getRightValue(me.chart.data.datasets[datasetIndex].data[index]); } // Format nicely - if (this.options.time.tooltipFormat) { - label = this.parseTime(label).format(this.options.time.tooltipFormat); + if (me.options.time.tooltipFormat) { + label = me.parseTime(label).format(me.options.time.tooltipFormat); } return label; @@ -317,29 +321,31 @@ module.exports = function(Chart) { } }, convertTicksToLabels: function() { - this.tickMoments = this.ticks; - this.ticks = this.ticks.map(this.tickFormatFunction, this); + var me = this; + me.tickMoments = me.ticks; + me.ticks = me.ticks.map(me.tickFormatFunction, me); }, getPixelForValue: function(value, index, datasetIndex, includeOffset) { - var labelMoment = value && value.isValid && value.isValid() ? value : this.getLabelMoment(datasetIndex, index); + var me = this; + var labelMoment = value && value.isValid && value.isValid() ? value : me.getLabelMoment(datasetIndex, index); if (labelMoment) { - var offset = labelMoment.diff(this.firstTick, this.tickUnit, true); + var offset = labelMoment.diff(me.firstTick, me.tickUnit, true); - var decimal = offset / this.scaleSizeInUnits; + var decimal = offset / me.scaleSizeInUnits; - if (this.isHorizontal()) { - var innerWidth = this.width - (this.paddingLeft + this.paddingRight); - var valueWidth = innerWidth / Math.max(this.ticks.length - 1, 1); - var valueOffset = (innerWidth * decimal) + this.paddingLeft; + if (me.isHorizontal()) { + var innerWidth = me.width - (me.paddingLeft + me.paddingRight); + var valueWidth = innerWidth / Math.max(me.ticks.length - 1, 1); + var valueOffset = (innerWidth * decimal) + me.paddingLeft; - return this.left + Math.round(valueOffset); + return me.left + Math.round(valueOffset); } else { - var innerHeight = this.height - (this.paddingTop + this.paddingBottom); - var valueHeight = innerHeight / Math.max(this.ticks.length - 1, 1); - var heightOffset = (innerHeight * decimal) + this.paddingTop; + var innerHeight = me.height - (me.paddingTop + me.paddingBottom); + var valueHeight = innerHeight / Math.max(me.ticks.length - 1, 1); + var heightOffset = (innerHeight * decimal) + me.paddingTop; - return this.top + Math.round(heightOffset); + return me.top + Math.round(heightOffset); } } }, @@ -347,17 +353,19 @@ module.exports = function(Chart) { return this.getPixelForValue(this.tickMoments[index], null, null, includeOffset); }, getValueForPixel: function(pixel) { - var innerDimension = this.isHorizontal() ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom); - var offset = (pixel - (this.isHorizontal() ? this.left + this.paddingLeft : this.top + this.paddingTop)) / innerDimension; - offset *= this.scaleSizeInUnits; - return this.firstTick.clone().add(moment.duration(offset, this.tickUnit).asSeconds(), 'seconds'); + var me = this; + var innerDimension = me.isHorizontal() ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom); + var offset = (pixel - (me.isHorizontal() ? me.left + me.paddingLeft : me.top + me.paddingTop)) / innerDimension; + offset *= me.scaleSizeInUnits; + return me.firstTick.clone().add(moment.duration(offset, me.tickUnit).asSeconds(), 'seconds'); }, parseTime: function(label) { - if (typeof this.options.time.parser === 'string') { - return moment(label, this.options.time.parser); + var me = this; + if (typeof me.options.time.parser === 'string') { + return moment(label, me.options.time.parser); } - if (typeof this.options.time.parser === 'function') { - return this.options.time.parser(label); + if (typeof me.options.time.parser === 'function') { + return me.options.time.parser(label); } // Date objects if (typeof label.getMonth === 'function' || typeof label === 'number') { @@ -368,12 +376,12 @@ module.exports = function(Chart) { return label; } // Custom parsing (return an instance of moment) - if (typeof this.options.time.format !== 'string' && this.options.time.format.call) { + if (typeof me.options.time.format !== 'string' && me.options.time.format.call) { console.warn("options.time.format is deprecated and replaced by options.time.parser. See http://nnnick.github.io/Chart.js/docs-v2/#scales-time-scale"); - return this.options.time.format(label); + return me.options.time.format(label); } // Moment format parsing - return moment(label, this.options.time.format); + return moment(label, me.options.time.format); } }); Chart.scaleService.registerScaleType("time", TimeScale, defaultConfig); -- 2.47.3