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