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') {
54 // Remove uninteresting bits: logging functions and paths.
55 st
= printStackTrace({guess
:false});
56 while (st
[0].indexOf("stacktrace") != -1) {
61 for (var i
= 0; i
< st
.length
; i
++) {
62 st
[i
] = st
[i
].replace(/\([^)]*\/(.*)\)/, '@$1')
63 .replace(/\@.*\/([^\/]*)/, '@$1')
64 .replace('[object Object].', '');
66 var top_msg
= st
.splice(0, 1)[0];
67 message
+= ' (' + top_msg
.replace(/^.*@ ?/, '') + ')';
70 if (typeof(console
) != 'undefined') {
73 console
.debug('dygraphs: ' + message
);
76 console
.info('dygraphs: ' + message
);
79 console
.warn('dygraphs: ' + message
);
82 console
.error('dygraphs: ' + message
);
87 if (Dygraph
.LOG_STACK_TRACES
) {
88 console
.log(st
.join('\n'));
93 Dygraph
.info
= function(message
) {
94 Dygraph
.log(Dygraph
.INFO
, message
);
97 Dygraph
.prototype.info
= Dygraph
.info
;
100 Dygraph
.warn
= function(message
) {
101 Dygraph
.log(Dygraph
.WARNING
, message
);
104 Dygraph
.prototype.warn
= Dygraph
.warn
;
107 Dygraph
.error
= function(message
) {
108 Dygraph
.log(Dygraph
.ERROR
, message
);
111 Dygraph
.prototype.error
= Dygraph
.error
;
115 * Return the 2d context for a dygraph canvas.
117 * This method is only exposed for the sake of replacing the function in
118 * automated tests, e.g.
120 * var oldFunc = Dygraph.getContext();
121 * Dygraph.getContext = function(canvas) {
122 * var realContext = oldFunc(canvas);
123 * return new Proxy(realContext);
126 Dygraph
.getContext
= function(canvas
) {
127 return canvas
.getContext("2d");
132 * Add an event handler. This smooths a difference between IE and the rest of
134 * @param { DOM element } elem The element to add the event to.
135 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
136 * @param { Function } fn The function to call on the event. The function takes
137 * one parameter: the event object.
139 Dygraph
.prototype.addEvent
= function addEvent(elem
, type
, fn
) {
140 if (elem
.addEventListener
) {
141 elem
.addEventListener(type
, fn
, false);
143 elem
[type
+fn
] = function(){fn(window
.event
);};
144 elem
.attachEvent('on'+type
, elem
[type
+fn
]);
146 this.registeredEvents_
.push({ elem
: elem
, type
: type
, fn
: fn
});
151 * Remove an event handler. This smooths a difference between IE and the rest of
153 * @param { DOM element } elem The element to add the event to.
154 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
155 * @param { Function } fn The function to call on the event. The function takes
156 * one parameter: the event object.
158 Dygraph
.prototype.removeEvent
= function addEvent(elem
, type
, fn
) {
159 if (elem
.removeEventListener
) {
160 elem
.removeEventListener(type
, fn
, false);
162 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
163 elem
[type
+fn
] = null;
169 * Cancels further processing of an event. This is useful to prevent default
170 * browser actions, e.g. highlighting text on a double-click.
171 * Based on the article at
172 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
173 * @param { Event } e The event whose normal behavior should be canceled.
175 Dygraph
.cancelEvent
= function(e
) {
176 e
= e
? e
: window
.event
;
177 if (e
.stopPropagation
) {
180 if (e
.preventDefault
) {
183 e
.cancelBubble
= true;
185 e
.returnValue
= false;
190 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
191 * is used to generate default series colors which are evenly spaced on the
193 * @param { Number } hue Range is 0.0-1.0.
194 * @param { Number } saturation Range is 0.0-1.0.
195 * @param { Number } value Range is 0.0-1.0.
196 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
199 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
203 if (saturation
=== 0) {
208 var i
= Math
.floor(hue
* 6);
209 var f
= (hue
* 6) - i
;
210 var p
= value
* (1 - saturation
);
211 var q
= value
* (1 - (saturation
* f
));
212 var t
= value
* (1 - (saturation
* (1 - f
)));
214 case 1: red
= q
; green
= value
; blue
= p
; break;
215 case 2: red
= p
; green
= value
; blue
= t
; break;
216 case 3: red
= p
; green
= q
; blue
= value
; break;
217 case 4: red
= t
; green
= p
; blue
= value
; break;
218 case 5: red
= value
; green
= p
; blue
= q
; break;
219 case 6: // fall through
220 case 0: red
= value
; green
= t
; blue
= p
; break;
223 red
= Math
.floor(255 * red
+ 0.5);
224 green
= Math
.floor(255 * green
+ 0.5);
225 blue
= Math
.floor(255 * blue
+ 0.5);
226 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
229 // The following functions are from quirksmode.org with a modification for Safari from
230 // http://blog.firetree.net/2005/07/04/javascript-find-position/
231 // http://www.quirksmode.org/js
/findpos
.html
232 // ... and modifications to support scrolling divs.
235 * Find the x-coordinate of the supplied object relative to the left side
239 Dygraph
.findPosX
= function(obj
) {
241 if(obj
.offsetParent
) {
244 curleft
+= copyObj
.offsetLeft
;
245 if(!copyObj
.offsetParent
) {
248 copyObj
= copyObj
.offsetParent
;
253 // This handles the case where the object is inside a scrolled div.
254 while(obj
&& obj
!= document
.body
) {
255 curleft
-= obj
.scrollLeft
;
256 obj
= obj
.parentNode
;
262 * Find the y-coordinate of the supplied object relative to the top of the
266 Dygraph
.findPosY
= function(obj
) {
268 if(obj
.offsetParent
) {
271 curtop
+= copyObj
.offsetTop
;
272 if(!copyObj
.offsetParent
) {
275 copyObj
= copyObj
.offsetParent
;
280 // This handles the case where the object is inside a scrolled div.
281 while(obj
&& obj
!= document
.body
) {
282 curtop
-= obj
.scrollTop
;
283 obj
= obj
.parentNode
;
290 * Returns the x-coordinate of the event in a coordinate system where the
291 * top-left corner of the page (not the window) is (0,0).
292 * Taken from MochiKit.Signal
294 Dygraph
.pageX
= function(e
) {
296 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
299 var b
= document
.body
;
301 (de
.scrollLeft
|| b
.scrollLeft
) -
302 (de
.clientLeft
|| 0);
308 * Returns the y-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
.pageY
= function(e
) {
314 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
317 var b
= document
.body
;
319 (de
.scrollTop
|| b
.scrollTop
) -
326 * @param { Number } x The number to consider.
327 * @return { Boolean } Whether the number is zero or NaN.
329 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
330 // TODO(danvk): determine when else this returns false (e.g. for undefined or null)
331 Dygraph
.isOK
= function(x
) {
332 return x
&& !isNaN(x
);
337 * @param { Object } p The point to consider, valid points are {x, y} objects
338 * @param { Boolean } allowNaNY Treat point with y=NaN as valid
339 * @return { Boolean } Whether the point has numeric x and y.
341 Dygraph
.isValidPoint
= function(p
, allowNaNY
) {
342 if (!p
) return false; // null or undefined object
343 if (p
.yval
=== null) return false; // missing point
344 if (p
.x
=== null || p
.x
=== undefined
) return false;
345 if (p
.y
=== null || p
.y
=== undefined
) return false;
346 if (isNaN(p
.x
) || (!allowNaNY
&& isNaN(p
.y
))) return false;
351 * Number formatting function which mimicks the behavior of %g in printf, i.e.
352 * either exponential or fixed format (without trailing 0s) is used depending on
353 * the length of the generated string. The advantage of this format is that
354 * there is a predictable upper bound on the resulting string length,
355 * significant figures are not dropped, and normal numbers are not displayed in
356 * exponential notation.
358 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
359 * It creates strings which are too long for absolute values between 10^-4 and
360 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
363 * @param {Number} x The number to format
364 * @param {Number} opt_precision The precision to use, default 2.
365 * @return {String} A string formatted like %g in printf. The max generated
366 * string length should be precision + 6 (e.g 1.123e+300).
368 Dygraph
.floatFormat
= function(x
, opt_precision
) {
369 // Avoid invalid precision values; [1, 21] is the valid range.
370 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
372 // This is deceptively simple. The actual algorithm comes from:
374 // Max allowed length = p + 4
375 // where 4 comes from 'e+n' and '.'.
377 // Length of fixed format = 2 + y + p
378 // where 2 comes from '0.' and y = # of leading zeroes.
380 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
383 // Since the behavior of toPrecision() is identical for larger numbers, we
384 // don't have to worry about the other bound.
386 // Finally, the argument for toExponential() is the number of trailing digits,
387 // so we take off 1 for the value before the '.'.
388 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
389 x
.toExponential(p
- 1) : x
.toPrecision(p
);
394 * Converts '9' to '09' (useful for dates)
396 Dygraph
.zeropad
= function(x
) {
397 if (x
< 10) return "0" + x
; else return "" + x
;
401 * Return a string version of the hours, minutes and seconds portion of a date.
402 * @param {Number} date The JavaScript date (ms since epoch)
403 * @return {String} A time of the form "HH:MM:SS"
406 Dygraph
.hmsString_
= function(date
) {
407 var zeropad
= Dygraph
.zeropad
;
408 var d
= new Date(date
);
409 if (d
.getSeconds()) {
410 return zeropad(d
.getHours()) + ":" +
411 zeropad(d
.getMinutes()) + ":" +
412 zeropad(d
.getSeconds());
414 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
419 * Round a number to the specified number of digits past the decimal point.
420 * @param {Number} num The number to round
421 * @param {Number} places The number of decimals to which to round
422 * @return {Number} The rounded number
425 Dygraph
.round_
= function(num
, places
) {
426 var shift
= Math
.pow(10, places
);
427 return Math
.round(num
* shift
)/shift
;
432 * Implementation of binary search over an array.
433 * Currently does not work when val is outside the range of arry's values.
434 * @param { Integer } val the value to search for
435 * @param { Integer[] } arry is the value over which to search
436 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
437 * If abs < 0, find the highest entry less than val.
438 * if abs == 0, find the entry that equals val.
439 * @param { Integer } [low] The first index in arry to consider (optional)
440 * @param { Integer } [high] The last index in arry to consider (optional)
442 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
443 if (low
=== null || low
=== undefined
||
444 high
=== null || high
=== undefined
) {
446 high
= arry
.length
- 1;
451 if (abs
=== null || abs
=== undefined
) {
454 var validIndex
= function(idx
) {
455 return idx
>= 0 && idx
< arry
.length
;
457 var mid
= parseInt((low
+ high
) / 2, 10);
458 var element
= arry
[mid
];
459 if (element
== val
) {
466 // Accept if element > val, but also if prior element < val.
468 if (validIndex(idx
) && arry
[idx
] < val
) {
472 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
476 // Accept if element < val, but also if prior element > val.
478 if (validIndex(idx
) && arry
[idx
] > val
) {
482 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
488 * Parses a date, returning the number of milliseconds since epoch. This can be
489 * passed in as an xValueParser in the Dygraph constructor.
490 * TODO(danvk): enumerate formats that this understands.
491 * @param {String} A date in YYYYMMDD format.
492 * @return {Number} Milliseconds since epoch.
494 Dygraph
.dateParser
= function(dateStr
) {
498 // Let the system try the format first, with one caveat:
499 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
500 // dygraphs displays dates in local time, so this will result in surprising
501 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
502 // then you probably know what you're doing, so we'll let you go ahead.
503 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
504 if (dateStr
.search("-") == -1 ||
505 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
506 d
= Dygraph
.dateStrToMillis(dateStr
);
507 if (d
&& !isNaN(d
)) return d
;
510 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
511 dateStrSlashed
= dateStr
.replace("-", "/", "g");
512 while (dateStrSlashed
.search("-") != -1) {
513 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
515 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
516 } else if (dateStr
.length
== 8) { // e.g. '20090712'
517 // TODO(danvk): remove support for this format. It's confusing.
518 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
520 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
522 // Any format that Date.parse will accept, e.g. "2009/07/12" or
523 // "2009/07/12 12:34:56"
524 d
= Dygraph
.dateStrToMillis(dateStr
);
527 if (!d
|| isNaN(d
)) {
528 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
535 * This is identical to JavaScript's built-in Date.parse() method, except that
536 * it doesn't get replaced with an incompatible method by aggressive JS
537 * libraries like MooTools or Joomla.
538 * @param { String } str The date string, e.g. "2011/05/06"
539 * @return { Integer } millis since epoch
541 Dygraph
.dateStrToMillis
= function(str
) {
542 return new Date(str
).getTime();
545 // These functions are all based on MochiKit.
547 * Copies all the properties from o to self.
551 Dygraph
.update
= function (self
, o
) {
552 if (typeof(o
) != 'undefined' && o
!== null) {
554 if (o
.hasOwnProperty(k
)) {
563 * Copies all the properties from o to self.
567 Dygraph
.updateDeep
= function (self
, o
) {
568 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
571 typeof Node
=== "object" ? o
instanceof Node
:
572 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
576 if (typeof(o
) != 'undefined' && o
!== null) {
578 if (o
.hasOwnProperty(k
)) {
581 } else if (Dygraph
.isArrayLike(o
[k
])) {
582 self
[k
] = o
[k
].slice();
583 } else if (isNode(o
[k
])) {
584 // DOM objects are shallowly-copied.
586 } else if (typeof(o
[k
]) == 'object') {
587 if (typeof(self
[k
]) != 'object') {
590 Dygraph
.updateDeep(self
[k
], o
[k
]);
603 Dygraph
.isArrayLike
= function (o
) {
606 (typ
!= 'object' && !(typ
== 'function' &&
607 typeof(o
.item
) == 'function')) ||
609 typeof(o
.length
) != 'number' ||
620 Dygraph
.isDateLike
= function (o
) {
621 if (typeof(o
) != "object" || o
=== null ||
622 typeof(o
.getTime
) != 'function') {
629 * Note: this only seems to work for arrays.
632 Dygraph
.clone
= function(o
) {
633 // TODO(danvk): figure out how MochiKit's version works
635 for (var i
= 0; i
< o
.length
; i
++) {
636 if (Dygraph
.isArrayLike(o
[i
])) {
637 r
.push(Dygraph
.clone(o
[i
]));
647 * Create a new canvas element. This is more complex than a simple
648 * document.createElement("canvas") because of IE and excanvas.
650 Dygraph
.createCanvas
= function() {
651 var canvas
= document
.createElement("canvas");
653 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
654 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
655 canvas
= G_vmlCanvasManager
.initElement(canvas
);
663 * Checks whether the user is on an Android browser.
664 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
666 Dygraph
.isAndroid
= function() {
667 return (/Android/).test(navigator
.userAgent
);
672 * Call a function N times at a given interval, then call a cleanup function
673 * once. repeat_fn is called once immediately, then (times - 1) times
674 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
675 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
676 * (from 0 to times-1) as an argument.
677 * @param times {number} The number of times to call repeat_fn
678 * @param every_ms {number} Milliseconds between calls
679 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
682 Dygraph
.repeatAndCleanup
= function(repeat_fn
, times
, every_ms
, cleanup_fn
) {
684 var start_time
= new Date().getTime();
692 if (count
>= times
) return;
693 var target_time
= start_time
+ (1 + count
) * every_ms
;
694 setTimeout(function() {
697 if (count
>= times
- 1) {
702 }, target_time
- new Date().getTime());
703 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
709 * This function will scan the option list and determine if they
710 * require us to recalculate the pixel positions of each point.
711 * @param { List } a list of options to check.
712 * @return { Boolean } true if the graph needs new points else false.
714 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
715 // A whitelist of options that do not change pixel positions.
716 var pixelSafeOptions
= {
717 'annotationClickHandler': true,
718 'annotationDblClickHandler': true,
719 'annotationMouseOutHandler': true,
720 'annotationMouseOverHandler': true,
721 'axisLabelColor': true,
722 'axisLineColor': true,
723 'axisLineWidth': true,
724 'clickCallback': true,
725 'digitsAfterDecimal': true,
726 'drawCallback': true,
727 'drawHighlightPointCallback': true,
729 'drawPointCallback': true,
733 'gridLineColor': true,
734 'gridLineWidth': true,
735 'hideOverlayOnMouseOut': true,
736 'highlightCallback': true,
737 'highlightCircleSize': true,
738 'interactionModel': true,
739 'isZoomedIgnoreProgrammaticZoom': true,
741 'labelsDivStyles': true,
742 'labelsDivWidth': true,
745 'labelsSeparateLines': true,
746 'labelsShowZeroValues': true,
748 'maxNumberWidth': true,
749 'panEdgeFraction': true,
750 'pixelsPerYLabel': true,
751 'pointClickCallback': true,
753 'rangeSelectorPlotFillColor': true,
754 'rangeSelectorPlotStrokeColor': true,
755 'showLabelsOnHighlight': true,
759 'underlayCallback': true,
760 'unhighlightCallback': true,
761 'xAxisLabelFormatter': true,
763 'xValueFormatter': true,
764 'yAxisLabelFormatter': true,
765 'yValueFormatter': true,
769 // Assume that we do not require new points.
770 // This will change to true if we actually do need new points.
771 var requiresNewPoints
= false;
773 // Create a dictionary of series names for faster lookup.
774 // If there are no labels, then the dictionary stays empty.
775 var seriesNamesDictionary
= { };
777 for (var i
= 1; i
< labels
.length
; i
++) {
778 seriesNamesDictionary
[labels
[i
]] = true;
782 // Iterate through the list of updated options.
783 for (var property
in attrs
) {
784 // Break early if we already know we need new points from a previous option.
785 if (requiresNewPoints
) {
788 if (attrs
.hasOwnProperty(property
)) {
789 // Find out of this field is actually a series specific options list.
790 if (seriesNamesDictionary
[property
]) {
791 // This property value is a list of options for this series.
792 // If any of these sub properties are not pixel safe, set the flag.
793 for (var subProperty
in attrs
[property
]) {
794 // Break early if we already know we need new points from a previous option.
795 if (requiresNewPoints
) {
798 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
799 requiresNewPoints
= true;
802 // If this was not a series specific option list, check if its a pixel changing property.
803 } else if (!pixelSafeOptions
[property
]) {
804 requiresNewPoints
= true;
809 return requiresNewPoints
;
813 * Compares two arrays to see if they are equal. If either parameter is not an
814 * array it will return false. Does a shallow compare
815 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
816 * @param array1 first array
817 * @param array2 second array
818 * @return True if both parameters are arrays, and contents are equal.
820 Dygraph
.compareArrays
= function(array1
, array2
) {
821 if (!Dygraph
.isArrayLike(array1
) || !Dygraph
.isArrayLike(array2
)) {
824 if (array1
.length
!== array2
.length
) {
827 for (var i
= 0; i
< array1
.length
; i
++) {
828 if (array1
[i
] !== array2
[i
]) {
836 * ctx: the canvas context
837 * sides: the number of sides in the shape.
838 * radius: the radius of the image.
839 * cx: center x coordate
840 * cy: center y coordinate
841 * rotationRadians: the shift of the initial angle, in radians.
842 * delta: the angle shift for each line. If missing, creates a regular
845 Dygraph
.regularShape_
= function(
846 ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
) {
847 rotationRadians
= rotationRadians
? rotationRadians
: 0;
848 delta
= delta
? delta
: Math
.PI
* 2 / sides
;
852 var initialAngle
= rotationRadians
;
853 var angle
= initialAngle
;
855 var computeCoordinates
= function() {
856 var x
= cx
+ (Math
.sin(angle
) * radius
);
857 var y
= cy
+ (-Math
.cos(angle
) * radius
);
861 var initialCoordinates
= computeCoordinates();
862 var x
= initialCoordinates
[0];
863 var y
= initialCoordinates
[1];
866 for (var idx
= 0; idx
< sides
; idx
++) {
867 angle
= (idx
== sides
- 1) ? initialAngle
: (angle
+ delta
);
868 var coords
= computeCoordinates();
869 ctx
.lineTo(coords
[0], coords
[1]);
875 Dygraph
.shapeFunction_
= function(sides
, rotationRadians
, delta
) {
876 return function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
877 ctx
.strokeStyle
= color
;
878 ctx
.fillStyle
= "white";
879 Dygraph
.regularShape_(ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
);
883 Dygraph
.DrawPolygon_
= function(sides
, rotationRadians
, ctx
, cx
, cy
, color
, radius
, delta
) {
884 new Dygraph
.RegularShape_(sides
, rotationRadians
, delta
).draw(ctx
, cx
, cy
, radius
);
888 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
890 ctx
.fillStyle
= color
;
891 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
894 TRIANGLE
: Dygraph
.shapeFunction_(3),
895 SQUARE
: Dygraph
.shapeFunction_(4, Math
.PI
/ 4),
896 DIAMOND
: Dygraph
.shapeFunction_(4),
897 PENTAGON
: Dygraph
.shapeFunction_(5),
898 HEXAGON
: Dygraph
.shapeFunction_(6),
899 CIRCLE
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
901 ctx
.strokeStyle
= color
;
902 ctx
.fillStyle
= "white";
903 ctx
.arc(cx
, cy
, radius
, 0, 2 * Math
.PI
, false);
907 STAR
: Dygraph
.shapeFunction_(5, 0, 4 * Math
.PI
/ 5),
908 PLUS
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
909 ctx
.strokeStyle
= color
;
912 ctx
.moveTo(cx
+ radius
, cy
);
913 ctx
.lineTo(cx
- radius
, cy
);
918 ctx
.moveTo(cx
, cy
+ radius
);
919 ctx
.lineTo(cx
, cy
- radius
);
923 EX
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
924 ctx
.strokeStyle
= color
;
927 ctx
.moveTo(cx
+ radius
, cy
+ radius
);
928 ctx
.lineTo(cx
- radius
, cy
- radius
);
933 ctx
.moveTo(cx
+ radius
, cy
- radius
);
934 ctx
.lineTo(cx
- radius
, cy
+ radius
);