Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveStatistics/sources/HeuristicLab.Services.Hive.Statistics/3.3/Scripts/smoothie.js @ 11020

Last change on this file since 11020 was 11020, checked in by mroscoe, 10 years ago

First check-in for Matt Roscoe. Major revision, multiple new files created and multiple files changed.

File size: 28.7 KB
Line 
1// MIT License:
2//
3// Copyright (c) 2010-2013, Joe Walnes
4//               2013-2014, Drew Noakes
5//
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12//
13// The above copyright notice and this permission notice shall be included in
14// all copies or substantial portions of the Software.
15//
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22// THE SOFTWARE.
23
24/**
25 * Smoothie Charts - http://smoothiecharts.org/
26 * (c) 2010-2013, Joe Walnes
27 *     2013-2014, Drew Noakes
28 *
29 * v1.0: Main charting library, by Joe Walnes
30 * v1.1: Auto scaling of axis, by Neil Dunn
31 * v1.2: fps (frames per second) option, by Mathias Petterson
32 * v1.3: Fix for divide by zero, by Paul Nikitochkin
33 * v1.4: Set minimum, top-scale padding, remove timeseries, add optional timer to reset bounds, by Kelley Reynolds
34 * v1.5: Set default frames per second to 50... smoother.
35 *       .start(), .stop() methods for conserving CPU, by Dmitry Vyal
36 *       options.interpolation = 'bezier' or 'line', by Dmitry Vyal
37 *       options.maxValue to fix scale, by Dmitry Vyal
38 * v1.6: minValue/maxValue will always get converted to floats, by Przemek Matylla
39 * v1.7: options.grid.fillStyle may be a transparent color, by Dmitry A. Shashkin
40 *       Smooth rescaling, by Kostas Michalopoulos
41 * v1.8: Set max length to customize number of live points in the dataset with options.maxDataSetLength, by Krishna Narni
42 * v1.9: Display timestamps along the bottom, by Nick and Stev-io
43 *       (https://groups.google.com/forum/?fromgroups#!topic/smoothie-charts/-Ywse8FCpKI%5B1-25%5D)
44 *       Refactored by Krishna Narni, to support timestamp formatting function
45 * v1.10: Switch to requestAnimationFrame, removed the now obsoleted options.fps, by Gergely Imreh
46 * v1.11: options.grid.sharpLines option added, by @drewnoakes
47 *        Addressed warning seen in Firefox when seriesOption.fillStyle undefined, by @drewnoakes
48 * v1.12: Support for horizontalLines added, by @drewnoakes
49 *        Support for yRangeFunction callback added, by @drewnoakes
50 * v1.13: Fixed typo (#32), by @alnikitich
51 * v1.14: Timer cleared when last TimeSeries removed (#23), by @davidgaleano
52 *        Fixed diagonal line on chart at start/end of data stream, by @drewnoakes
53 * v1.15: Support for npm package (#18), by @dominictarr
54 *        Fixed broken removeTimeSeries function (#24) by @davidgaleano
55 *        Minor performance and tidying, by @drewnoakes
56 * v1.16: Bug fix introduced in v1.14 relating to timer creation/clearance (#23), by @drewnoakes
57 *        TimeSeries.append now deals with out-of-order timestamps, and can merge duplicates, by @zacwitte (#12)
58 *        Documentation and some local variable renaming for clarity, by @drewnoakes
59 * v1.17: Allow control over font size (#10), by @drewnoakes
60 *        Timestamp text won't overlap, by @drewnoakes
61 * v1.18: Allow control of max/min label precision, by @drewnoakes
62 *        Added 'borderVisible' chart option, by @drewnoakes
63 *        Allow drawing series with fill but no stroke (line), by @drewnoakes
64 * v1.19: Avoid unnecessary repaints, and fixed flicker in old browsers having multiple charts in document (#40), by @asbai
65 * v1.20: Add SmoothieChart.getTimeSeriesOptions and SmoothieChart.bringToFront functions, by @drewnoakes
66 * v1.21: Add 'step' interpolation mode, by @drewnoakes
67 * v1.22: Add support for different pixel ratios. Also add optional y limit formatters, by @copacetic
68 * v1.23: Fix bug introduced in v1.22 (#44), by @drewnoakes
69 */
70
71;(function(exports) {
72
73  var Util = {
74    extend: function() {
75      arguments[0] = arguments[0] || {};
76      for (var i = 1; i < arguments.length; i++)
77      {
78        for (var key in arguments[i])
79        {
80          if (arguments[i].hasOwnProperty(key))
81          {
82            if (typeof(arguments[i][key]) === 'object') {
83              if (arguments[i][key] instanceof Array) {
84                arguments[0][key] = arguments[i][key];
85              } else {
86                arguments[0][key] = Util.extend(arguments[0][key], arguments[i][key]);
87              }
88            } else {
89              arguments[0][key] = arguments[i][key];
90            }
91          }
92        }
93      }
94      return arguments[0];
95    }
96  };
97
98  /**
99   * Initialises a new <code>TimeSeries</code> with optional data options.
100   *
101   * Options are of the form (defaults shown):
102   *
103   * <pre>
104   * {
105   *   resetBounds: true,        // enables/disables automatic scaling of the y-axis
106   *   resetBoundsInterval: 3000 // the period between scaling calculations, in millis
107   * }
108   * </pre>
109   *
110   * Presentation options for TimeSeries are specified as an argument to <code>SmoothieChart.addTimeSeries</code>.
111   *
112   * @constructor
113   */
114  function TimeSeries(options) {
115    this.options = Util.extend({}, TimeSeries.defaultOptions, options);
116    this.data = [];
117    this.maxValue = Number.NaN; // The maximum value ever seen in this TimeSeries.
118    this.minValue = Number.NaN; // The minimum value ever seen in this TimeSeries.
119  }
120
121  TimeSeries.defaultOptions = {
122    resetBoundsInterval: 3000,
123    resetBounds: true
124  };
125
126  /**
127   * Recalculate the min/max values for this <code>TimeSeries</code> object.
128   *
129   * This causes the graph to scale itself in the y-axis.
130   */
131  TimeSeries.prototype.resetBounds = function() {
132    if (this.data.length) {
133      // Walk through all data points, finding the min/max value
134      this.maxValue = this.data[0][1];
135      this.minValue = this.data[0][1];
136      for (var i = 1; i < this.data.length; i++) {
137        var value = this.data[i][1];
138        if (value > this.maxValue) {
139          this.maxValue = value;
140        }
141        if (value < this.minValue) {
142          this.minValue = value;
143        }
144      }
145    } else {
146      // No data exists, so set min/max to NaN
147      this.maxValue = Number.NaN;
148      this.minValue = Number.NaN;
149    }
150  };
151
152  /**
153   * Adds a new data point to the <code>TimeSeries</code>, preserving chronological order.
154   *
155   * @param timestamp the position, in time, of this data point
156   * @param value the value of this data point
157   * @param sumRepeatedTimeStampValues if <code>timestamp</code> has an exact match in the series, this flag controls
158   * whether it is replaced, or the values summed (defaults to false.)
159   */
160  TimeSeries.prototype.append = function(timestamp, value, sumRepeatedTimeStampValues) {
161    // Rewind until we hit an older timestamp
162    var i = this.data.length - 1;
163    while (i > 0 && this.data[i][0] > timestamp) {
164      i--;
165    }
166
167    if (this.data.length > 0 && this.data[i][0] === timestamp) {
168      // Update existing values in the array
169      if (sumRepeatedTimeStampValues) {
170        // Sum this value into the existing 'bucket'
171        this.data[i][1] += value;
172        value = this.data[i][1];
173      } else {
174        // Replace the previous value
175        this.data[i][1] = value;
176      }
177    } else if (i < this.data.length - 1) {
178      // Splice into the correct position to keep timestamps in order
179      this.data.splice(i + 1, 0, [timestamp, value]);
180    } else {
181      // Add to the end of the array
182      this.data.push([timestamp, value]);
183    }
184
185    this.maxValue = isNaN(this.maxValue) ? value : Math.max(this.maxValue, value);
186    this.minValue = isNaN(this.minValue) ? value : Math.min(this.minValue, value);
187  };
188
189  TimeSeries.prototype.dropOldData = function(oldestValidTime, maxDataSetLength) {
190    // We must always keep one expired data point as we need this to draw the
191    // line that comes into the chart from the left, but any points prior to that can be removed.
192    var removeCount = 0;
193    while (this.data.length - removeCount >= maxDataSetLength && this.data[removeCount + 1][0] < oldestValidTime) {
194      removeCount++;
195    }
196    if (removeCount !== 0) {
197      this.data.splice(0, removeCount);
198    }
199  };
200
201  /**
202   * Initialises a new <code>SmoothieChart</code>.
203   *
204   * Options are optional, and should be of the form below. Just specify the values you
205   * need and the rest will be given sensible defaults as shown:
206   *
207   * <pre>
208   * {
209   *   minValue: undefined,                      // specify to clamp the lower y-axis to a given value
210   *   maxValue: undefined,                      // specify to clamp the upper y-axis to a given value
211   *   maxValueScale: 1,                         // allows proportional padding to be added above the chart. for 10% padding, specify 1.1.
212   *   yRangeFunction: undefined,                // function({min: , max: }) { return {min: , max: }; }
213   *   scaleSmoothing: 0.125,                    // controls the rate at which y-value zoom animation occurs
214   *   millisPerPixel: 20,                       // sets the speed at which the chart pans by
215   *   enableDpiScaling: true,                   // support rendering at different DPI depending on the device
216   *   yMinFormatter: function(min, precision) { // callback function that formats the min y value label
217   *     return min.toFixed(precision);
218   *   },
219   *   yMaxFormatter: function(max, precision) { // callback function that formats the max y value label
220   *     return max.toFixed(precision);
221   *   },
222   *   maxDataSetLength: 2,
223   *   interpolation: 'bezier'                   // one of 'bezier', 'linear', or 'step'
224   *   timestampFormatter: null,                 // optional function to format time stamps for bottom of chart
225   *                                             // you may use SmoothieChart.timeFormatter, or your own: function(date) { return ''; }
226   *   horizontalLines: [],                      // [ { value: 0, color: '#ffffff', lineWidth: 1 } ]
227   *   grid:
228   *   {
229   *     fillStyle: '#000000',                   // the background colour of the chart
230   *     lineWidth: 1,                           // the pixel width of grid lines
231   *     strokeStyle: '#777777',                 // colour of grid lines
232   *     millisPerLine: 1000,                    // distance between vertical grid lines
233   *     sharpLines: false,                      // controls whether grid lines are 1px sharp, or softened
234   *     verticalSections: 2,                    // number of vertical sections marked out by horizontal grid lines
235   *     borderVisible: true                     // whether the grid lines trace the border of the chart or not
236   *   },
237   *   labels
238   *   {
239   *     disabled: false,                        // enables/disables labels showing the min/max values
240   *     fillStyle: '#ffffff',                   // colour for text of labels,
241   *     fontSize: 15,
242   *     fontFamily: 'sans-serif',
243   *     precision: 2
244   *   }
245   * }
246   * </pre>
247   *
248   * @constructor
249   */
250  function SmoothieChart(options) {
251    this.options = Util.extend({}, SmoothieChart.defaultChartOptions, options);
252    this.seriesSet = [];
253    this.currentValueRange = 1;
254    this.currentVisMinValue = 0;
255    this.lastRenderTimeMillis = 0;
256  }
257
258  SmoothieChart.defaultChartOptions = {
259    millisPerPixel: 20,
260    enableDpiScaling: true,
261    yMinFormatter: function(min, precision) { return min.toFixed(precision); },
262    yMaxFormatter: function(max, precision) { return max.toFixed(precision); },
263    maxValueScale: 1,
264    interpolation: 'bezier',
265    scaleSmoothing: 0.125,
266    maxDataSetLength: 2,
267    grid: {
268      fillStyle: '#000000',
269      strokeStyle: '#777777',
270      lineWidth: 1,
271      sharpLines: false,
272      millisPerLine: 1000,
273      verticalSections: 2,
274      borderVisible: true
275    },
276    labels: {
277      fillStyle: '#ffffff',
278      disabled: false,
279      fontSize: 10,
280      fontFamily: 'monospace',
281      precision: 2
282    },
283    horizontalLines: []
284  };
285
286  // Based on http://inspirit.github.com/jsfeat/js/compatibility.js
287  SmoothieChart.AnimateCompatibility = (function() {
288    var requestAnimationFrame = function(callback, element) {
289          var requestAnimationFrame =
290            window.requestAnimationFrame        ||
291            window.webkitRequestAnimationFrame  ||
292            window.mozRequestAnimationFrame     ||
293            window.oRequestAnimationFrame       ||
294            window.msRequestAnimationFrame      ||
295            function(callback) {
296              return window.setTimeout(function() {
297                callback(new Date().getTime());
298              }, 16);
299            };
300          return requestAnimationFrame.call(window, callback, element);
301        },
302        cancelAnimationFrame = function(id) {
303          var cancelAnimationFrame =
304            window.cancelAnimationFrame ||
305            function(id) {
306              clearTimeout(id);
307            };
308          return cancelAnimationFrame.call(window, id);
309        };
310
311    return {
312      requestAnimationFrame: requestAnimationFrame,
313      cancelAnimationFrame: cancelAnimationFrame
314    };
315  })();
316
317  SmoothieChart.defaultSeriesPresentationOptions = {
318    lineWidth: 1,
319    strokeStyle: '#ffffff'
320  };
321
322  /**
323   * Adds a <code>TimeSeries</code> to this chart, with optional presentation options.
324   *
325   * Presentation options should be of the form (defaults shown):
326   *
327   * <pre>
328   * {
329   *   lineWidth: 1,
330   *   strokeStyle: '#ffffff',
331   *   fillStyle: undefined
332   * }
333   * </pre>
334   */
335  SmoothieChart.prototype.addTimeSeries = function(timeSeries, options) {
336    this.seriesSet.push({timeSeries: timeSeries, options: Util.extend({}, SmoothieChart.defaultSeriesPresentationOptions, options)});
337    if (timeSeries.options.resetBounds && timeSeries.options.resetBoundsInterval > 0) {
338      timeSeries.resetBoundsTimerId = setInterval(
339        function() {
340          timeSeries.resetBounds();
341        },
342        timeSeries.options.resetBoundsInterval
343      );
344    }
345  };
346
347  /**
348   * Removes the specified <code>TimeSeries</code> from the chart.
349   */
350  SmoothieChart.prototype.removeTimeSeries = function(timeSeries) {
351    // Find the correct timeseries to remove, and remove it
352    var numSeries = this.seriesSet.length;
353    for (var i = 0; i < numSeries; i++) {
354      if (this.seriesSet[i].timeSeries === timeSeries) {
355        this.seriesSet.splice(i, 1);
356        break;
357      }
358    }
359    // If a timer was operating for that timeseries, remove it
360    if (timeSeries.resetBoundsTimerId) {
361      // Stop resetting the bounds, if we were
362      clearInterval(timeSeries.resetBoundsTimerId);
363    }
364  };
365
366  /**
367   * Gets render options for the specified <code>TimeSeries</code>.
368   *
369   * As you may use a single <code>TimeSeries</code> in multiple charts with different formatting in each usage,
370   * these settings are stored in the chart.
371   */
372  SmoothieChart.prototype.getTimeSeriesOptions = function(timeSeries) {
373    // Find the correct timeseries to remove, and remove it
374    var numSeries = this.seriesSet.length;
375    for (var i = 0; i < numSeries; i++) {
376      if (this.seriesSet[i].timeSeries === timeSeries) {
377        return this.seriesSet[i].options;
378      }
379    }
380  };
381
382  /**
383   * Brings the specified <code>TimeSeries</code> to the top of the chart. It will be rendered last.
384   */
385  SmoothieChart.prototype.bringToFront = function(timeSeries) {
386    // Find the correct timeseries to remove, and remove it
387    var numSeries = this.seriesSet.length;
388    for (var i = 0; i < numSeries; i++) {
389      if (this.seriesSet[i].timeSeries === timeSeries) {
390        var set = this.seriesSet.splice(i, 1);
391        this.seriesSet.push(set[0]);
392        break;
393      }
394    }
395  };
396
397  /**
398   * Instructs the <code>SmoothieChart</code> to start rendering to the provided canvas, with specified delay.
399   *
400   * @param canvas the target canvas element
401   * @param delayMillis an amount of time to wait before a data point is shown. This can prevent the end of the series
402   * from appearing on screen, with new values flashing into view, at the expense of some latency.
403   */
404  SmoothieChart.prototype.streamTo = function(canvas, delayMillis) {
405    this.canvas = canvas;
406    this.delay = delayMillis;
407    this.start();
408  };
409
410  /**
411   * Starts the animation of this chart.
412   */
413  SmoothieChart.prototype.start = function() {
414    if (this.frame) {
415      // We're already running, so just return
416      return;
417    }
418    // Make sure the canvas has the optimal resolution for the device's pixel ratio.
419    if (this.options.enableDpiScaling && window && window.devicePixelRatio !== 1) {
420      var canvasWidth = this.canvas.getAttribute('width');
421      var canvasHeight = this.canvas.getAttribute('height');
422
423      this.canvas.setAttribute('width', canvasWidth * window.devicePixelRatio);
424      this.canvas.setAttribute('height', canvasHeight * window.devicePixelRatio);
425      this.canvas.style.width = canvasWidth + 'px';
426      this.canvas.style.height = canvasHeight + 'px';
427      this.canvas.getContext('2d').scale(window.devicePixelRatio, window.devicePixelRatio);
428    }
429
430    // Renders a frame, and queues the next frame for later rendering
431    var animate = function() {
432      this.frame = SmoothieChart.AnimateCompatibility.requestAnimationFrame(function() {
433        this.render();
434        animate();
435      }.bind(this));
436    }.bind(this);
437
438    animate();
439  };
440
441  /**
442   * Stops the animation of this chart.
443   */
444  SmoothieChart.prototype.stop = function() {
445    if (this.frame) {
446      SmoothieChart.AnimateCompatibility.cancelAnimationFrame(this.frame);
447      delete this.frame;
448    }
449  };
450
451  SmoothieChart.prototype.updateValueRange = function() {
452    // Calculate the current scale of the chart, from all time series.
453    var chartOptions = this.options,
454        chartMaxValue = Number.NaN,
455        chartMinValue = Number.NaN;
456
457    for (var d = 0; d < this.seriesSet.length; d++) {
458      // TODO(ndunn): We could calculate / track these values as they stream in.
459      var timeSeries = this.seriesSet[d].timeSeries;
460      if (!isNaN(timeSeries.maxValue)) {
461        chartMaxValue = !isNaN(chartMaxValue) ? Math.max(chartMaxValue, timeSeries.maxValue) : timeSeries.maxValue;
462      }
463
464      if (!isNaN(timeSeries.minValue)) {
465        chartMinValue = !isNaN(chartMinValue) ? Math.min(chartMinValue, timeSeries.minValue) : timeSeries.minValue;
466      }
467    }
468
469    // Scale the chartMaxValue to add padding at the top if required
470    if (chartOptions.maxValue != null) {
471      chartMaxValue = chartOptions.maxValue;
472    } else {
473      chartMaxValue *= chartOptions.maxValueScale;
474    }
475
476    // Set the minimum if we've specified one
477    if (chartOptions.minValue != null) {
478      chartMinValue = chartOptions.minValue;
479    }
480
481    // If a custom range function is set, call it
482    if (this.options.yRangeFunction) {
483      var range = this.options.yRangeFunction({min: chartMinValue, max: chartMaxValue});
484      chartMinValue = range.min;
485      chartMaxValue = range.max;
486    }
487
488    if (!isNaN(chartMaxValue) && !isNaN(chartMinValue)) {
489      var targetValueRange = chartMaxValue - chartMinValue;
490      var valueRangeDiff = (targetValueRange - this.currentValueRange);
491      var minValueDiff = (chartMinValue - this.currentVisMinValue);
492      this.isAnimatingScale = Math.abs(valueRangeDiff) > 0.1 || Math.abs(minValueDiff) > 0.1;
493      this.currentValueRange += chartOptions.scaleSmoothing * valueRangeDiff;
494      this.currentVisMinValue += chartOptions.scaleSmoothing * minValueDiff;
495    }
496
497    this.valueRange = { min: chartMinValue, max: chartMaxValue };
498  };
499
500  SmoothieChart.prototype.render = function(canvas, time) {
501    var nowMillis = new Date().getTime();
502
503    if (!this.isAnimatingScale) {
504      // We're not animating. We can use the last render time and the scroll speed to work out whether
505      // we actually need to paint anything yet. If not, we can return immediately.
506
507      // Render at least every 1/6th of a second. The canvas may be resized, which there is
508      // no reliable way to detect.
509      var maxIdleMillis = Math.min(1000/6, this.options.millisPerPixel);
510
511      if (nowMillis - this.lastRenderTimeMillis < maxIdleMillis) {
512        return;
513      }
514    }
515    this.lastRenderTimeMillis = nowMillis;
516
517    canvas = canvas || this.canvas;
518    time = time || nowMillis - (this.delay || 0);
519
520    // Round time down to pixel granularity, so motion appears smoother.
521    time -= time % this.options.millisPerPixel;
522
523    var context = canvas.getContext('2d'),
524        chartOptions = this.options,
525        dimensions = { top: 0, left: 0, width: canvas.clientWidth, height: canvas.clientHeight },
526        // Calculate the threshold time for the oldest data points.
527        oldestValidTime = time - (dimensions.width * chartOptions.millisPerPixel),
528        valueToYPixel = function(value) {
529          var offset = value - this.currentVisMinValue;
530          return this.currentValueRange === 0
531            ? dimensions.height
532            : dimensions.height - (Math.round((offset / this.currentValueRange) * dimensions.height));
533        }.bind(this),
534        timeToXPixel = function(t) {
535          return Math.round(dimensions.width - ((time - t) / chartOptions.millisPerPixel));
536        };
537
538    this.updateValueRange();
539
540    context.font = chartOptions.labels.fontSize + 'px ' + chartOptions.labels.fontFamily;
541
542    // Save the state of the canvas context, any transformations applied in this method
543    // will get removed from the stack at the end of this method when .restore() is called.
544    context.save();
545
546    // Move the origin.
547    context.translate(dimensions.left, dimensions.top);
548
549    // Create a clipped rectangle - anything we draw will be constrained to this rectangle.
550    // This prevents the occasional pixels from curves near the edges overrunning and creating
551    // screen cheese (that phrase should need no explanation).
552    context.beginPath();
553    context.rect(0, 0, dimensions.width, dimensions.height);
554    context.clip();
555
556    // Clear the working area.
557    context.save();
558    context.fillStyle = chartOptions.grid.fillStyle;
559    context.clearRect(0, 0, dimensions.width, dimensions.height);
560    context.fillRect(0, 0, dimensions.width, dimensions.height);
561    context.restore();
562
563    // Grid lines...
564    context.save();
565    context.lineWidth = chartOptions.grid.lineWidth;
566    context.strokeStyle = chartOptions.grid.strokeStyle;
567    // Vertical (time) dividers.
568    if (chartOptions.grid.millisPerLine > 0) {
569      var textUntilX = dimensions.width - context.measureText(minValueString).width + 4;
570      for (var t = time - (time % chartOptions.grid.millisPerLine);
571           t >= oldestValidTime;
572           t -= chartOptions.grid.millisPerLine) {
573        var gx = timeToXPixel(t);
574        if (chartOptions.grid.sharpLines) {
575          gx -= 0.5;
576        }
577        context.beginPath();
578        context.moveTo(gx, 0);
579        context.lineTo(gx, dimensions.height);
580        context.stroke();
581        context.closePath();
582
583        // Display timestamp at bottom of this line if requested, and it won't overlap
584        if (chartOptions.timestampFormatter && gx < textUntilX) {
585          // Formats the timestamp based on user specified formatting function
586          // SmoothieChart.timeFormatter function above is one such formatting option
587          var tx = new Date(t),
588            ts = chartOptions.timestampFormatter(tx),
589            tsWidth = context.measureText(ts).width;
590          textUntilX = gx - tsWidth - 2;
591          context.fillStyle = chartOptions.labels.fillStyle;
592          context.fillText(ts, gx - tsWidth, dimensions.height - 2);
593        }
594      }
595    }
596
597    // Horizontal (value) dividers.
598    for (var v = 1; v < chartOptions.grid.verticalSections; v++) {
599      var gy = Math.round(v * dimensions.height / chartOptions.grid.verticalSections);
600      if (chartOptions.grid.sharpLines) {
601        gy -= 0.5;
602      }
603      context.beginPath();
604      context.moveTo(0, gy);
605      context.lineTo(dimensions.width, gy);
606      context.stroke();
607      context.closePath();
608    }
609    // Bounding rectangle.
610    if (chartOptions.grid.borderVisible) {
611      context.beginPath();
612      context.strokeRect(0, 0, dimensions.width, dimensions.height);
613      context.closePath();
614    }
615    context.restore();
616
617    // Draw any horizontal lines...
618    if (chartOptions.horizontalLines && chartOptions.horizontalLines.length) {
619      for (var hl = 0; hl < chartOptions.horizontalLines.length; hl++) {
620        var line = chartOptions.horizontalLines[hl],
621            hly = Math.round(valueToYPixel(line.value)) - 0.5;
622        context.strokeStyle = line.color || '#ffffff';
623        context.lineWidth = line.lineWidth || 1;
624        context.beginPath();
625        context.moveTo(0, hly);
626        context.lineTo(dimensions.width, hly);
627        context.stroke();
628        context.closePath();
629      }
630    }
631
632    // For each data set...
633    for (var d = 0; d < this.seriesSet.length; d++) {
634      context.save();
635      var timeSeries = this.seriesSet[d].timeSeries,
636          dataSet = timeSeries.data,
637          seriesOptions = this.seriesSet[d].options;
638
639      // Delete old data that's moved off the left of the chart.
640      timeSeries.dropOldData(oldestValidTime, chartOptions.maxDataSetLength);
641
642      // Set style for this dataSet.
643      context.lineWidth = seriesOptions.lineWidth;
644      context.strokeStyle = seriesOptions.strokeStyle;
645      // Draw the line...
646      context.beginPath();
647      // Retain lastX, lastY for calculating the control points of bezier curves.
648      var firstX = 0, lastX = 0, lastY = 0;
649      for (var i = 0; i < dataSet.length && dataSet.length !== 1; i++) {
650        var x = timeToXPixel(dataSet[i][0]),
651            y = valueToYPixel(dataSet[i][1]);
652
653        if (i === 0) {
654          firstX = x;
655          context.moveTo(x, y);
656        } else {
657          switch (chartOptions.interpolation) {
658            case "linear":
659            case "line": {
660              context.lineTo(x,y);
661              break;
662            }
663            case "bezier":
664            default: {
665              // Great explanation of Bezier curves: http://en.wikipedia.org/wiki/Bezier_curve#Quadratic_curves
666              //
667              // Assuming A was the last point in the line plotted and B is the new point,
668              // we draw a curve with control points P and Q as below.
669              //
670              // A---P
671              //     |
672              //     |
673              //     |
674              //     Q---B
675              //
676              // Importantly, A and P are at the same y coordinate, as are B and Q. This is
677              // so adjacent curves appear to flow as one.
678              //
679              context.bezierCurveTo( // startPoint (A) is implicit from last iteration of loop
680                Math.round((lastX + x) / 2), lastY, // controlPoint1 (P)
681                Math.round((lastX + x)) / 2, y, // controlPoint2 (Q)
682                x, y); // endPoint (B)
683              break;
684            }
685            case "step": {
686              context.lineTo(x,lastY);
687              context.lineTo(x,y);
688              break;
689            }
690          }
691        }
692
693        lastX = x; lastY = y;
694      }
695
696      if (dataSet.length > 1) {
697        if (seriesOptions.fillStyle) {
698          // Close up the fill region.
699          context.lineTo(dimensions.width + seriesOptions.lineWidth + 1, lastY);
700          context.lineTo(dimensions.width + seriesOptions.lineWidth + 1, dimensions.height + seriesOptions.lineWidth + 1);
701          context.lineTo(firstX, dimensions.height + seriesOptions.lineWidth);
702          context.fillStyle = seriesOptions.fillStyle;
703          context.fill();
704        }
705
706        if (seriesOptions.strokeStyle && seriesOptions.strokeStyle !== 'none') {
707          context.stroke();
708        }
709        context.closePath();
710      }
711      context.restore();
712    }
713
714    // Draw the axis values on the chart.
715    if (!chartOptions.labels.disabled && !isNaN(this.valueRange.min) && !isNaN(this.valueRange.max)) {
716      var maxValueString = chartOptions.yMaxFormatter(this.valueRange.max, chartOptions.labels.precision),
717          minValueString = chartOptions.yMinFormatter(this.valueRange.min, chartOptions.labels.precision);
718      context.fillStyle = chartOptions.labels.fillStyle;
719      context.fillText(maxValueString, dimensions.width - context.measureText(maxValueString).width - 2, chartOptions.labels.fontSize);
720      context.fillText(minValueString, dimensions.width - context.measureText(minValueString).width - 2, dimensions.height - 2);
721    }
722
723    context.restore(); // See .save() above.
724  };
725
726  // Sample timestamp formatting function
727  SmoothieChart.timeFormatter = function(date) {
728    function pad2(number) { return (number < 10 ? '0' : '') + number }
729    return pad2(date.getHours()) + ':' + pad2(date.getMinutes()) + ':' + pad2(date.getSeconds());
730  };
731
732  exports.TimeSeries = TimeSeries;
733  exports.SmoothieChart = SmoothieChart;
734
735})(typeof exports === 'undefined' ? this : exports);
736
Note: See TracBrowser for help on using the repository browser.