3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
8 * @fileoverview This file contains utility functions used by dygraphs. These
9 * are typically static (i.e. not related to any particular dygraph). Examples
10 * include date/time formatting functions, basic algorithms (e.g. binary
11 * search) and generic DOM-manipulation functions.
14 /*jshint globalstrict: true */
15 /*global Dygraph:false, G_vmlCanvasManager:false, Node:false, printStackTrace: false */
18 Dygraph
.LOG_SCALE
= 10;
19 Dygraph
.LN_TEN
= Math
.log(Dygraph
.LOG_SCALE
);
22 Dygraph
.log10
= function(x
) {
23 return Math
.log(x
) / Dygraph
.LN_TEN
;
26 // Various logging levels.
32 // Set this to log stack traces on warnings, etc.
33 // This requires stacktrace.js, which is up to you to provide.
34 // A copy can be found in the dygraphs repo, or at
35 // https://github.com/eriwen
/javascript
-stacktrace
36 Dygraph
.LOG_STACK_TRACES
= false;
38 /** A dotted line stroke pattern. */
39 Dygraph
.DOTTED_LINE
= [2, 2];
40 /** A dashed line stroke pattern. */
41 Dygraph
.DASHED_LINE
= [7, 3];
42 /** A dot dash stroke pattern. */
43 Dygraph
.DOT_DASH_LINE
= [7, 2, 2, 2];
47 * Log an error on the JS console at the given severity.
48 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
49 * @param { String } The message to log.
51 Dygraph
.log
= function(severity
, message
) {
53 if (typeof(printStackTrace
) != 'undefined') {
55 // Remove uninteresting bits: logging functions and paths.
56 st
= printStackTrace({guess
:false});
57 while (st
[0].indexOf("stacktrace") != -1) {
62 for (var i
= 0; i
< st
.length
; i
++) {
63 st
[i
] = st
[i
].replace(/\([^)]*\/(.*)\)/, '@$1')
64 .replace(/\@.*\/([^\/]*)/, '@$1')
65 .replace('[object Object].', '');
67 var top_msg
= st
.splice(0, 1)[0];
68 message
+= ' (' + top_msg
.replace(/^.*@ ?/, '') + ')';
70 // Oh well, it was worth a shot!
74 if (typeof(console
) != 'undefined') {
77 console
.debug('dygraphs: ' + message
);
80 console
.info('dygraphs: ' + message
);
83 console
.warn('dygraphs: ' + message
);
86 console
.error('dygraphs: ' + message
);
91 if (Dygraph
.LOG_STACK_TRACES
) {
92 console
.log(st
.join('\n'));
97 Dygraph
.info
= function(message
) {
98 Dygraph
.log(Dygraph
.INFO
, message
);
101 Dygraph
.prototype.info
= Dygraph
.info
;
104 Dygraph
.warn
= function(message
) {
105 Dygraph
.log(Dygraph
.WARNING
, message
);
108 Dygraph
.prototype.warn
= Dygraph
.warn
;
111 Dygraph
.error
= function(message
) {
112 Dygraph
.log(Dygraph
.ERROR
, message
);
115 Dygraph
.prototype.error
= Dygraph
.error
;
119 * Return the 2d context for a dygraph canvas.
121 * This method is only exposed for the sake of replacing the function in
122 * automated tests, e.g.
124 * var oldFunc = Dygraph.getContext();
125 * Dygraph.getContext = function(canvas) {
126 * var realContext = oldFunc(canvas);
127 * return new Proxy(realContext);
130 Dygraph
.getContext
= function(canvas
) {
131 return canvas
.getContext("2d");
136 * Add an event handler. This smooths a difference between IE and the rest of
138 * @param { DOM element } elem The element to add the event to.
139 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
140 * @param { Function } fn The function to call on the event. The function takes
141 * one parameter: the event object.
143 Dygraph
.addEvent
= function addEvent(elem
, type
, fn
) {
144 if (elem
.addEventListener
) {
145 elem
.addEventListener(type
, fn
, false);
147 elem
[type
+fn
] = function(){fn(window
.event
);};
148 elem
.attachEvent('on'+type
, elem
[type
+fn
]);
154 * Add an event handler. This event handler is kept until the graph is
155 * destroyed with a call to graph.destroy().
157 * @param { DOM element } elem The element to add the event to.
158 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
159 * @param { Function } fn The function to call on the event. The function takes
160 * one parameter: the event object.
162 Dygraph
.prototype.addEvent
= function addEvent(elem
, type
, fn
) {
163 Dygraph
.addEvent(elem
, type
, fn
);
164 this.registeredEvents_
.push({ elem
: elem
, type
: type
, fn
: fn
});
169 * Remove an event handler. This smooths a difference between IE and the rest of
171 * @param { DOM element } elem The element to add the event to.
172 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
173 * @param { Function } fn The function to call on the event. The function takes
174 * one parameter: the event object.
176 Dygraph
.removeEvent
= function addEvent(elem
, type
, fn
) {
177 if (elem
.removeEventListener
) {
178 elem
.removeEventListener(type
, fn
, false);
180 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
181 elem
[type
+fn
] = null;
187 * Cancels further processing of an event. This is useful to prevent default
188 * browser actions, e.g. highlighting text on a double-click.
189 * Based on the article at
190 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
191 * @param { Event } e The event whose normal behavior should be canceled.
193 Dygraph
.cancelEvent
= function(e
) {
194 e
= e
? e
: window
.event
;
195 if (e
.stopPropagation
) {
198 if (e
.preventDefault
) {
201 e
.cancelBubble
= true;
203 e
.returnValue
= false;
208 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
209 * is used to generate default series colors which are evenly spaced on the
211 * @param { Number } hue Range is 0.0-1.0.
212 * @param { Number } saturation Range is 0.0-1.0.
213 * @param { Number } value Range is 0.0-1.0.
214 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
217 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
221 if (saturation
=== 0) {
226 var i
= Math
.floor(hue
* 6);
227 var f
= (hue
* 6) - i
;
228 var p
= value
* (1 - saturation
);
229 var q
= value
* (1 - (saturation
* f
));
230 var t
= value
* (1 - (saturation
* (1 - f
)));
232 case 1: red
= q
; green
= value
; blue
= p
; break;
233 case 2: red
= p
; green
= value
; blue
= t
; break;
234 case 3: red
= p
; green
= q
; blue
= value
; break;
235 case 4: red
= t
; green
= p
; blue
= value
; break;
236 case 5: red
= value
; green
= p
; blue
= q
; break;
237 case 6: // fall through
238 case 0: red
= value
; green
= t
; blue
= p
; break;
241 red
= Math
.floor(255 * red
+ 0.5);
242 green
= Math
.floor(255 * green
+ 0.5);
243 blue
= Math
.floor(255 * blue
+ 0.5);
244 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
247 // The following functions are from quirksmode.org with a modification for Safari from
248 // http://blog.firetree.net/2005/07/04/javascript-find-position/
249 // http://www.quirksmode.org/js
/findpos
.html
250 // ... and modifications to support scrolling divs.
253 * Find the x-coordinate of the supplied object relative to the left side
257 Dygraph
.findPosX
= function(obj
) {
259 if(obj
.offsetParent
) {
262 curleft
+= copyObj
.offsetLeft
;
263 if(!copyObj
.offsetParent
) {
266 copyObj
= copyObj
.offsetParent
;
271 // This handles the case where the object is inside a scrolled div.
272 while(obj
&& obj
!= document
.body
) {
273 curleft
-= obj
.scrollLeft
;
274 obj
= obj
.parentNode
;
280 * Find the y-coordinate of the supplied object relative to the top of the
284 Dygraph
.findPosY
= function(obj
) {
286 if(obj
.offsetParent
) {
289 curtop
+= copyObj
.offsetTop
;
290 if(!copyObj
.offsetParent
) {
293 copyObj
= copyObj
.offsetParent
;
298 // This handles the case where the object is inside a scrolled div.
299 while(obj
&& obj
!= document
.body
) {
300 curtop
-= obj
.scrollTop
;
301 obj
= obj
.parentNode
;
308 * Returns the x-coordinate of the event in a coordinate system where the
309 * top-left corner of the page (not the window) is (0,0).
310 * Taken from MochiKit.Signal
312 Dygraph
.pageX
= function(e
) {
314 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
317 var b
= document
.body
;
319 (de
.scrollLeft
|| b
.scrollLeft
) -
320 (de
.clientLeft
|| 0);
326 * Returns the y-coordinate of the event in a coordinate system where the
327 * top-left corner of the page (not the window) is (0,0).
328 * Taken from MochiKit.Signal
330 Dygraph
.pageY
= function(e
) {
332 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
335 var b
= document
.body
;
337 (de
.scrollTop
|| b
.scrollTop
) -
344 * @param { Number } x The number to consider.
345 * @return { Boolean } Whether the number is zero or NaN.
347 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
348 // TODO(danvk): determine when else this returns false (e.g. for undefined or null)
349 Dygraph
.isOK
= function(x
) {
350 return x
&& !isNaN(x
);
355 * @param { Object } p The point to consider, valid points are {x, y} objects
356 * @param { Boolean } allowNaNY Treat point with y=NaN as valid
357 * @return { Boolean } Whether the point has numeric x and y.
359 Dygraph
.isValidPoint
= function(p
, allowNaNY
) {
360 if (!p
) return false; // null or undefined object
361 if (p
.yval
=== null) return false; // missing point
362 if (p
.x
=== null || p
.x
=== undefined
) return false;
363 if (p
.y
=== null || p
.y
=== undefined
) return false;
364 if (isNaN(p
.x
) || (!allowNaNY
&& isNaN(p
.y
))) return false;
369 * Number formatting function which mimicks the behavior of %g in printf, i.e.
370 * either exponential or fixed format (without trailing 0s) is used depending on
371 * the length of the generated string. The advantage of this format is that
372 * there is a predictable upper bound on the resulting string length,
373 * significant figures are not dropped, and normal numbers are not displayed in
374 * exponential notation.
376 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
377 * It creates strings which are too long for absolute values between 10^-4 and
378 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
381 * @param {Number} x The number to format
382 * @param {Number} opt_precision The precision to use, default 2.
383 * @return {String} A string formatted like %g in printf. The max generated
384 * string length should be precision + 6 (e.g 1.123e+300).
386 Dygraph
.floatFormat
= function(x
, opt_precision
) {
387 // Avoid invalid precision values; [1, 21] is the valid range.
388 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
390 // This is deceptively simple. The actual algorithm comes from:
392 // Max allowed length = p + 4
393 // where 4 comes from 'e+n' and '.'.
395 // Length of fixed format = 2 + y + p
396 // where 2 comes from '0.' and y = # of leading zeroes.
398 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
401 // Since the behavior of toPrecision() is identical for larger numbers, we
402 // don't have to worry about the other bound.
404 // Finally, the argument for toExponential() is the number of trailing digits,
405 // so we take off 1 for the value before the '.'.
406 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
407 x
.toExponential(p
- 1) : x
.toPrecision(p
);
412 * Converts '9' to '09' (useful for dates)
414 Dygraph
.zeropad
= function(x
) {
415 if (x
< 10) return "0" + x
; else return "" + x
;
419 * Return a string version of the hours, minutes and seconds portion of a date.
420 * @param {Number} date The JavaScript date (ms since epoch)
421 * @return {String} A time of the form "HH:MM:SS"
424 Dygraph
.hmsString_
= function(date
) {
425 var zeropad
= Dygraph
.zeropad
;
426 var d
= new Date(date
);
427 if (d
.getSeconds()) {
428 return zeropad(d
.getHours()) + ":" +
429 zeropad(d
.getMinutes()) + ":" +
430 zeropad(d
.getSeconds());
432 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
437 * Round a number to the specified number of digits past the decimal point.
438 * @param {Number} num The number to round
439 * @param {Number} places The number of decimals to which to round
440 * @return {Number} The rounded number
443 Dygraph
.round_
= function(num
, places
) {
444 var shift
= Math
.pow(10, places
);
445 return Math
.round(num
* shift
)/shift
;
450 * Implementation of binary search over an array.
451 * Currently does not work when val is outside the range of arry's values.
452 * @param { Integer } val the value to search for
453 * @param { Integer[] } arry is the value over which to search
454 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
455 * If abs < 0, find the highest entry less than val.
456 * if abs == 0, find the entry that equals val.
457 * @param { Integer } [low] The first index in arry to consider (optional)
458 * @param { Integer } [high] The last index in arry to consider (optional)
460 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
461 if (low
=== null || low
=== undefined
||
462 high
=== null || high
=== undefined
) {
464 high
= arry
.length
- 1;
469 if (abs
=== null || abs
=== undefined
) {
472 var validIndex
= function(idx
) {
473 return idx
>= 0 && idx
< arry
.length
;
475 var mid
= parseInt((low
+ high
) / 2, 10);
476 var element
= arry
[mid
];
477 if (element
== val
) {
484 // Accept if element > val, but also if prior element < val.
486 if (validIndex(idx
) && arry
[idx
] < val
) {
490 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
494 // Accept if element < val, but also if prior element > val.
496 if (validIndex(idx
) && arry
[idx
] > val
) {
500 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
506 * Parses a date, returning the number of milliseconds since epoch. This can be
507 * passed in as an xValueParser in the Dygraph constructor.
508 * TODO(danvk): enumerate formats that this understands.
509 * @param {String} A date in YYYYMMDD format.
510 * @return {Number} Milliseconds since epoch.
512 Dygraph
.dateParser
= function(dateStr
) {
516 // Let the system try the format first, with one caveat:
517 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
518 // dygraphs displays dates in local time, so this will result in surprising
519 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
520 // then you probably know what you're doing, so we'll let you go ahead.
521 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
522 if (dateStr
.search("-") == -1 ||
523 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
524 d
= Dygraph
.dateStrToMillis(dateStr
);
525 if (d
&& !isNaN(d
)) return d
;
528 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
529 dateStrSlashed
= dateStr
.replace("-", "/", "g");
530 while (dateStrSlashed
.search("-") != -1) {
531 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
533 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
534 } else if (dateStr
.length
== 8) { // e.g. '20090712'
535 // TODO(danvk): remove support for this format. It's confusing.
536 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
538 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
540 // Any format that Date.parse will accept, e.g. "2009/07/12" or
541 // "2009/07/12 12:34:56"
542 d
= Dygraph
.dateStrToMillis(dateStr
);
545 if (!d
|| isNaN(d
)) {
546 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
553 * This is identical to JavaScript's built-in Date.parse() method, except that
554 * it doesn't get replaced with an incompatible method by aggressive JS
555 * libraries like MooTools or Joomla.
556 * @param { String } str The date string, e.g. "2011/05/06"
557 * @return { Integer } millis since epoch
559 Dygraph
.dateStrToMillis
= function(str
) {
560 return new Date(str
).getTime();
563 // These functions are all based on MochiKit.
565 * Copies all the properties from o to self.
569 Dygraph
.update
= function (self
, o
) {
570 if (typeof(o
) != 'undefined' && o
!== null) {
572 if (o
.hasOwnProperty(k
)) {
581 * Copies all the properties from o to self.
585 Dygraph
.updateDeep
= function (self
, o
) {
586 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
589 typeof Node
=== "object" ? o
instanceof Node
:
590 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
594 if (typeof(o
) != 'undefined' && o
!== null) {
596 if (o
.hasOwnProperty(k
)) {
599 } else if (Dygraph
.isArrayLike(o
[k
])) {
600 self
[k
] = o
[k
].slice();
601 } else if (isNode(o
[k
])) {
602 // DOM objects are shallowly-copied.
604 } else if (typeof(o
[k
]) == 'object') {
605 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
608 Dygraph
.updateDeep(self
[k
], o
[k
]);
621 Dygraph
.isArrayLike
= function (o
) {
624 (typ
!= 'object' && !(typ
== 'function' &&
625 typeof(o
.item
) == 'function')) ||
627 typeof(o
.length
) != 'number' ||
638 Dygraph
.isDateLike
= function (o
) {
639 if (typeof(o
) != "object" || o
=== null ||
640 typeof(o
.getTime
) != 'function') {
647 * Note: this only seems to work for arrays.
650 Dygraph
.clone
= function(o
) {
651 // TODO(danvk): figure out how MochiKit's version works
653 for (var i
= 0; i
< o
.length
; i
++) {
654 if (Dygraph
.isArrayLike(o
[i
])) {
655 r
.push(Dygraph
.clone(o
[i
]));
665 * Create a new canvas element. This is more complex than a simple
666 * document.createElement("canvas") because of IE and excanvas.
668 Dygraph
.createCanvas
= function() {
669 var canvas
= document
.createElement("canvas");
671 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
672 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
673 canvas
= G_vmlCanvasManager
.initElement(canvas
);
681 * Checks whether the user is on an Android browser.
682 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
684 Dygraph
.isAndroid
= function() {
685 return (/Android/).test(navigator
.userAgent
);
688 Dygraph
.Iterator
= function(array
, start
, length
, predicate
) {
690 length
= length
|| array
.length
;
691 this.hasNext
= true; // Use to identify if there's another element.
692 this.peek
= null; // Use for look-ahead
695 this.predicate_
= predicate
;
696 this.end_
= Math
.min(array
.length
, start
+ length
);
697 this.nextIdx_
= start
- 1; // use -1 so initial advance works.
698 this.next(); // ignoring result.
701 Dygraph
.Iterator
.prototype.next
= function() {
707 var nextIdx
= this.nextIdx_
+ 1;
709 while (nextIdx
< this.end_
) {
710 if (!this.predicate_
|| this.predicate_(this.array_
, nextIdx
)) {
711 this.peek
= this.array_
[nextIdx
];
717 this.nextIdx_
= nextIdx
;
719 this.hasNext
= false;
727 * Returns a new iterator over array, between indexes start and
728 * start + length, and only returns entries that pass the accept function
730 * @param array the array to iterate over.
731 * @param start the first index to iterate over, 0 if absent.
732 * @param length the number of elements in the array to iterate over.
733 * This, along with start, defines a slice of the array, and so length
734 * doesn't imply the number of elements in the iterator when accept
735 * doesn't always accept all values. array.length when absent.
736 * @param predicate a function that takes parameters array and idx, which
737 * returns true when the element should be returned. If omitted, all
738 * elements are accepted.
740 Dygraph
.createIterator
= function(array
, start
, length
, predicate
) {
741 return new Dygraph
.Iterator(array
, start
, length
, predicate
);
746 * Call a function N times at a given interval, then call a cleanup function
747 * once. repeat_fn is called once immediately, then (times - 1) times
748 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
749 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
750 * (from 0 to times-1) as an argument.
751 * @param times {number} The number of times to call repeat_fn
752 * @param every_ms {number} Milliseconds between calls
753 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
756 Dygraph
.repeatAndCleanup
= function(repeat_fn
, times
, every_ms
, cleanup_fn
) {
758 var start_time
= new Date().getTime();
766 if (count
>= times
) return;
767 var target_time
= start_time
+ (1 + count
) * every_ms
;
768 setTimeout(function() {
771 if (count
>= times
- 1) {
776 }, target_time
- new Date().getTime());
777 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
783 * This function will scan the option list and determine if they
784 * require us to recalculate the pixel positions of each point.
785 * @param { List } a list of options to check.
786 * @return { Boolean } true if the graph needs new points else false.
788 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
789 // A whitelist of options that do not change pixel positions.
790 var pixelSafeOptions
= {
791 'annotationClickHandler': true,
792 'annotationDblClickHandler': true,
793 'annotationMouseOutHandler': true,
794 'annotationMouseOverHandler': true,
795 'axisLabelColor': true,
796 'axisLineColor': true,
797 'axisLineWidth': true,
798 'clickCallback': true,
799 'digitsAfterDecimal': true,
800 'drawCallback': true,
801 'drawHighlightPointCallback': true,
803 'drawPointCallback': true,
807 'gridLineColor': true,
808 'gridLineWidth': true,
809 'hideOverlayOnMouseOut': true,
810 'highlightCallback': true,
811 'highlightCircleSize': true,
812 'interactionModel': true,
813 'isZoomedIgnoreProgrammaticZoom': true,
815 'labelsDivStyles': true,
816 'labelsDivWidth': true,
819 'labelsSeparateLines': true,
820 'labelsShowZeroValues': true,
822 'maxNumberWidth': true,
823 'panEdgeFraction': true,
824 'pixelsPerYLabel': true,
825 'pointClickCallback': true,
827 'rangeSelectorPlotFillColor': true,
828 'rangeSelectorPlotStrokeColor': true,
829 'showLabelsOnHighlight': true,
833 'underlayCallback': true,
834 'unhighlightCallback': true,
835 'xAxisLabelFormatter': true,
837 'xValueFormatter': true,
838 'yAxisLabelFormatter': true,
839 'yValueFormatter': true,
843 // Assume that we do not require new points.
844 // This will change to true if we actually do need new points.
845 var requiresNewPoints
= false;
847 // Create a dictionary of series names for faster lookup.
848 // If there are no labels, then the dictionary stays empty.
849 var seriesNamesDictionary
= { };
851 for (var i
= 1; i
< labels
.length
; i
++) {
852 seriesNamesDictionary
[labels
[i
]] = true;
856 // Iterate through the list of updated options.
857 for (var property
in attrs
) {
858 // Break early if we already know we need new points from a previous option.
859 if (requiresNewPoints
) {
862 if (attrs
.hasOwnProperty(property
)) {
863 // Find out of this field is actually a series specific options list.
864 if (seriesNamesDictionary
[property
]) {
865 // This property value is a list of options for this series.
866 // If any of these sub properties are not pixel safe, set the flag.
867 for (var subProperty
in attrs
[property
]) {
868 // Break early if we already know we need new points from a previous option.
869 if (requiresNewPoints
) {
872 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
873 requiresNewPoints
= true;
876 // If this was not a series specific option list, check if its a pixel changing property.
877 } else if (!pixelSafeOptions
[property
]) {
878 requiresNewPoints
= true;
883 return requiresNewPoints
;
887 * Compares two arrays to see if they are equal. If either parameter is not an
888 * array it will return false. Does a shallow compare
889 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
890 * @param array1 first array
891 * @param array2 second array
892 * @return True if both parameters are arrays, and contents are equal.
894 Dygraph
.compareArrays
= function(array1
, array2
) {
895 if (!Dygraph
.isArrayLike(array1
) || !Dygraph
.isArrayLike(array2
)) {
898 if (array1
.length
!== array2
.length
) {
901 for (var i
= 0; i
< array1
.length
; i
++) {
902 if (array1
[i
] !== array2
[i
]) {
910 * ctx: the canvas context
911 * sides: the number of sides in the shape.
912 * radius: the radius of the image.
913 * cx: center x coordate
914 * cy: center y coordinate
915 * rotationRadians: the shift of the initial angle, in radians.
916 * delta: the angle shift for each line. If missing, creates a regular
919 Dygraph
.regularShape_
= function(
920 ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
) {
921 rotationRadians
= rotationRadians
? rotationRadians
: 0;
922 delta
= delta
? delta
: Math
.PI
* 2 / sides
;
926 var initialAngle
= rotationRadians
;
927 var angle
= initialAngle
;
929 var computeCoordinates
= function() {
930 var x
= cx
+ (Math
.sin(angle
) * radius
);
931 var y
= cy
+ (-Math
.cos(angle
) * radius
);
935 var initialCoordinates
= computeCoordinates();
936 var x
= initialCoordinates
[0];
937 var y
= initialCoordinates
[1];
940 for (var idx
= 0; idx
< sides
; idx
++) {
941 angle
= (idx
== sides
- 1) ? initialAngle
: (angle
+ delta
);
942 var coords
= computeCoordinates();
943 ctx
.lineTo(coords
[0], coords
[1]);
949 Dygraph
.shapeFunction_
= function(sides
, rotationRadians
, delta
) {
950 return function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
951 ctx
.strokeStyle
= color
;
952 ctx
.fillStyle
= "white";
953 Dygraph
.regularShape_(ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
);
957 Dygraph
.DrawPolygon_
= function(sides
, rotationRadians
, ctx
, cx
, cy
, color
, radius
, delta
) {
958 new Dygraph
.RegularShape_(sides
, rotationRadians
, delta
).draw(ctx
, cx
, cy
, radius
);
962 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
964 ctx
.fillStyle
= color
;
965 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
968 TRIANGLE
: Dygraph
.shapeFunction_(3),
969 SQUARE
: Dygraph
.shapeFunction_(4, Math
.PI
/ 4),
970 DIAMOND
: Dygraph
.shapeFunction_(4),
971 PENTAGON
: Dygraph
.shapeFunction_(5),
972 HEXAGON
: Dygraph
.shapeFunction_(6),
973 CIRCLE
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
975 ctx
.strokeStyle
= color
;
976 ctx
.fillStyle
= "white";
977 ctx
.arc(cx
, cy
, radius
, 0, 2 * Math
.PI
, false);
981 STAR
: Dygraph
.shapeFunction_(5, 0, 4 * Math
.PI
/ 5),
982 PLUS
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
983 ctx
.strokeStyle
= color
;
986 ctx
.moveTo(cx
+ radius
, cy
);
987 ctx
.lineTo(cx
- radius
, cy
);
992 ctx
.moveTo(cx
, cy
+ radius
);
993 ctx
.lineTo(cx
, cy
- radius
);
997 EX
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
998 ctx
.strokeStyle
= color
;
1001 ctx
.moveTo(cx
+ radius
, cy
+ radius
);
1002 ctx
.lineTo(cx
- radius
, cy
- radius
);
1007 ctx
.moveTo(cx
+ radius
, cy
- radius
);
1008 ctx
.lineTo(cx
- radius
, cy
+ radius
);