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
.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
]);
150 * Add an event handler. This event handler is kept until the graph is
151 * destroyed with a call to graph.destroy().
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.addEvent
= function addEvent(elem
, type
, fn
) {
159 Dygraph
.addEvent(elem
, type
, fn
);
160 this.registeredEvents_
.push({ elem
: elem
, type
: type
, fn
: fn
});
165 * Remove an event handler. This smooths a difference between IE and the rest of
167 * @param { DOM element } elem The element to add the event to.
168 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
169 * @param { Function } fn The function to call on the event. The function takes
170 * one parameter: the event object.
172 Dygraph
.removeEvent
= function addEvent(elem
, type
, fn
) {
173 if (elem
.removeEventListener
) {
174 elem
.removeEventListener(type
, fn
, false);
176 elem
.detachEvent('on'+type
, elem
[type
+fn
]);
177 elem
[type
+fn
] = null;
183 * Cancels further processing of an event. This is useful to prevent default
184 * browser actions, e.g. highlighting text on a double-click.
185 * Based on the article at
186 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
187 * @param { Event } e The event whose normal behavior should be canceled.
189 Dygraph
.cancelEvent
= function(e
) {
190 e
= e
? e
: window
.event
;
191 if (e
.stopPropagation
) {
194 if (e
.preventDefault
) {
197 e
.cancelBubble
= true;
199 e
.returnValue
= false;
204 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
205 * is used to generate default series colors which are evenly spaced on the
207 * @param { Number } hue Range is 0.0-1.0.
208 * @param { Number } saturation Range is 0.0-1.0.
209 * @param { Number } value Range is 0.0-1.0.
210 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
213 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
217 if (saturation
=== 0) {
222 var i
= Math
.floor(hue
* 6);
223 var f
= (hue
* 6) - i
;
224 var p
= value
* (1 - saturation
);
225 var q
= value
* (1 - (saturation
* f
));
226 var t
= value
* (1 - (saturation
* (1 - f
)));
228 case 1: red
= q
; green
= value
; blue
= p
; break;
229 case 2: red
= p
; green
= value
; blue
= t
; break;
230 case 3: red
= p
; green
= q
; blue
= value
; break;
231 case 4: red
= t
; green
= p
; blue
= value
; break;
232 case 5: red
= value
; green
= p
; blue
= q
; break;
233 case 6: // fall through
234 case 0: red
= value
; green
= t
; blue
= p
; break;
237 red
= Math
.floor(255 * red
+ 0.5);
238 green
= Math
.floor(255 * green
+ 0.5);
239 blue
= Math
.floor(255 * blue
+ 0.5);
240 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
243 // The following functions are from quirksmode.org with a modification for Safari from
244 // http://blog.firetree.net/2005/07/04/javascript-find-position/
245 // http://www.quirksmode.org/js
/findpos
.html
246 // ... and modifications to support scrolling divs.
249 * Find the x-coordinate of the supplied object relative to the left side
253 Dygraph
.findPosX
= function(obj
) {
255 if(obj
.offsetParent
) {
258 curleft
+= copyObj
.offsetLeft
;
259 if(!copyObj
.offsetParent
) {
262 copyObj
= copyObj
.offsetParent
;
267 // This handles the case where the object is inside a scrolled div.
268 while(obj
&& obj
!= document
.body
) {
269 curleft
-= obj
.scrollLeft
;
270 obj
= obj
.parentNode
;
276 * Find the y-coordinate of the supplied object relative to the top of the
280 Dygraph
.findPosY
= function(obj
) {
282 if(obj
.offsetParent
) {
285 curtop
+= copyObj
.offsetTop
;
286 if(!copyObj
.offsetParent
) {
289 copyObj
= copyObj
.offsetParent
;
294 // This handles the case where the object is inside a scrolled div.
295 while(obj
&& obj
!= document
.body
) {
296 curtop
-= obj
.scrollTop
;
297 obj
= obj
.parentNode
;
304 * Returns the x-coordinate of the event in a coordinate system where the
305 * top-left corner of the page (not the window) is (0,0).
306 * Taken from MochiKit.Signal
308 Dygraph
.pageX
= function(e
) {
310 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
313 var b
= document
.body
;
315 (de
.scrollLeft
|| b
.scrollLeft
) -
316 (de
.clientLeft
|| 0);
322 * Returns the y-coordinate of the event in a coordinate system where the
323 * top-left corner of the page (not the window) is (0,0).
324 * Taken from MochiKit.Signal
326 Dygraph
.pageY
= function(e
) {
328 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
331 var b
= document
.body
;
333 (de
.scrollTop
|| b
.scrollTop
) -
340 * @param { Number } x The number to consider.
341 * @return { Boolean } Whether the number is zero or NaN.
343 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
344 // TODO(danvk): determine when else this returns false (e.g. for undefined or null)
345 Dygraph
.isOK
= function(x
) {
346 return x
&& !isNaN(x
);
351 * @param { Object } p The point to consider, valid points are {x, y} objects
352 * @param { Boolean } allowNaNY Treat point with y=NaN as valid
353 * @return { Boolean } Whether the point has numeric x and y.
355 Dygraph
.isValidPoint
= function(p
, allowNaNY
) {
356 if (!p
) return false; // null or undefined object
357 if (p
.yval
=== null) return false; // missing point
358 if (p
.x
=== null || p
.x
=== undefined
) return false;
359 if (p
.y
=== null || p
.y
=== undefined
) return false;
360 if (isNaN(p
.x
) || (!allowNaNY
&& isNaN(p
.y
))) return false;
365 * Number formatting function which mimicks the behavior of %g in printf, i.e.
366 * either exponential or fixed format (without trailing 0s) is used depending on
367 * the length of the generated string. The advantage of this format is that
368 * there is a predictable upper bound on the resulting string length,
369 * significant figures are not dropped, and normal numbers are not displayed in
370 * exponential notation.
372 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
373 * It creates strings which are too long for absolute values between 10^-4 and
374 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
377 * @param {Number} x The number to format
378 * @param {Number} opt_precision The precision to use, default 2.
379 * @return {String} A string formatted like %g in printf. The max generated
380 * string length should be precision + 6 (e.g 1.123e+300).
382 Dygraph
.floatFormat
= function(x
, opt_precision
) {
383 // Avoid invalid precision values; [1, 21] is the valid range.
384 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
386 // This is deceptively simple. The actual algorithm comes from:
388 // Max allowed length = p + 4
389 // where 4 comes from 'e+n' and '.'.
391 // Length of fixed format = 2 + y + p
392 // where 2 comes from '0.' and y = # of leading zeroes.
394 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
397 // Since the behavior of toPrecision() is identical for larger numbers, we
398 // don't have to worry about the other bound.
400 // Finally, the argument for toExponential() is the number of trailing digits,
401 // so we take off 1 for the value before the '.'.
402 return (Math
.abs(x
) < 1.0e-3 && x
!== 0.0) ?
403 x
.toExponential(p
- 1) : x
.toPrecision(p
);
408 * Converts '9' to '09' (useful for dates)
410 Dygraph
.zeropad
= function(x
) {
411 if (x
< 10) return "0" + x
; else return "" + x
;
415 * Return a string version of the hours, minutes and seconds portion of a date.
416 * @param {Number} date The JavaScript date (ms since epoch)
417 * @return {String} A time of the form "HH:MM:SS"
420 Dygraph
.hmsString_
= function(date
) {
421 var zeropad
= Dygraph
.zeropad
;
422 var d
= new Date(date
);
423 if (d
.getSeconds()) {
424 return zeropad(d
.getHours()) + ":" +
425 zeropad(d
.getMinutes()) + ":" +
426 zeropad(d
.getSeconds());
428 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
433 * Round a number to the specified number of digits past the decimal point.
434 * @param {Number} num The number to round
435 * @param {Number} places The number of decimals to which to round
436 * @return {Number} The rounded number
439 Dygraph
.round_
= function(num
, places
) {
440 var shift
= Math
.pow(10, places
);
441 return Math
.round(num
* shift
)/shift
;
446 * Implementation of binary search over an array.
447 * Currently does not work when val is outside the range of arry's values.
448 * @param { Integer } val the value to search for
449 * @param { Integer[] } arry is the value over which to search
450 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
451 * If abs < 0, find the highest entry less than val.
452 * if abs == 0, find the entry that equals val.
453 * @param { Integer } [low] The first index in arry to consider (optional)
454 * @param { Integer } [high] The last index in arry to consider (optional)
456 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
457 if (low
=== null || low
=== undefined
||
458 high
=== null || high
=== undefined
) {
460 high
= arry
.length
- 1;
465 if (abs
=== null || abs
=== undefined
) {
468 var validIndex
= function(idx
) {
469 return idx
>= 0 && idx
< arry
.length
;
471 var mid
= parseInt((low
+ high
) / 2, 10);
472 var element
= arry
[mid
];
473 if (element
== val
) {
480 // Accept if element > val, but also if prior element < val.
482 if (validIndex(idx
) && arry
[idx
] < val
) {
486 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
490 // Accept if element < val, but also if prior element > val.
492 if (validIndex(idx
) && arry
[idx
] > val
) {
496 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
502 * Parses a date, returning the number of milliseconds since epoch. This can be
503 * passed in as an xValueParser in the Dygraph constructor.
504 * TODO(danvk): enumerate formats that this understands.
505 * @param {String} A date in YYYYMMDD format.
506 * @return {Number} Milliseconds since epoch.
508 Dygraph
.dateParser
= function(dateStr
) {
512 // Let the system try the format first, with one caveat:
513 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
514 // dygraphs displays dates in local time, so this will result in surprising
515 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
516 // then you probably know what you're doing, so we'll let you go ahead.
517 // Issue: http://code.google.com/p/dygraphs/issues/detail
?id
=255
518 if (dateStr
.search("-") == -1 ||
519 dateStr
.search("T") != -1 || dateStr
.search("Z") != -1) {
520 d
= Dygraph
.dateStrToMillis(dateStr
);
521 if (d
&& !isNaN(d
)) return d
;
524 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
525 dateStrSlashed
= dateStr
.replace("-", "/", "g");
526 while (dateStrSlashed
.search("-") != -1) {
527 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
529 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
530 } else if (dateStr
.length
== 8) { // e.g. '20090712'
531 // TODO(danvk): remove support for this format. It's confusing.
532 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
534 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
536 // Any format that Date.parse will accept, e.g. "2009/07/12" or
537 // "2009/07/12 12:34:56"
538 d
= Dygraph
.dateStrToMillis(dateStr
);
541 if (!d
|| isNaN(d
)) {
542 Dygraph
.error("Couldn't parse " + dateStr
+ " as a date");
549 * This is identical to JavaScript's built-in Date.parse() method, except that
550 * it doesn't get replaced with an incompatible method by aggressive JS
551 * libraries like MooTools or Joomla.
552 * @param { String } str The date string, e.g. "2011/05/06"
553 * @return { Integer } millis since epoch
555 Dygraph
.dateStrToMillis
= function(str
) {
556 return new Date(str
).getTime();
559 // These functions are all based on MochiKit.
561 * Copies all the properties from o to self.
565 Dygraph
.update
= function (self
, o
) {
566 if (typeof(o
) != 'undefined' && o
!== null) {
568 if (o
.hasOwnProperty(k
)) {
577 * Copies all the properties from o to self.
581 Dygraph
.updateDeep
= function (self
, o
) {
582 // Taken from http://stackoverflow.com/questions
/384286/javascript
-isdom
-how
-do-you
-check
-if-a
-javascript
-object
-is
-a
-dom
-object
585 typeof Node
=== "object" ? o
instanceof Node
:
586 typeof o
=== "object" && typeof o
.nodeType
=== "number" && typeof o
.nodeName
==="string"
590 if (typeof(o
) != 'undefined' && o
!== null) {
592 if (o
.hasOwnProperty(k
)) {
595 } else if (Dygraph
.isArrayLike(o
[k
])) {
596 self
[k
] = o
[k
].slice();
597 } else if (isNode(o
[k
])) {
598 // DOM objects are shallowly-copied.
600 } else if (typeof(o
[k
]) == 'object') {
601 if (typeof(self
[k
]) != 'object' || self
[k
] === null) {
604 Dygraph
.updateDeep(self
[k
], o
[k
]);
617 Dygraph
.isArrayLike
= function (o
) {
620 (typ
!= 'object' && !(typ
== 'function' &&
621 typeof(o
.item
) == 'function')) ||
623 typeof(o
.length
) != 'number' ||
634 Dygraph
.isDateLike
= function (o
) {
635 if (typeof(o
) != "object" || o
=== null ||
636 typeof(o
.getTime
) != 'function') {
643 * Note: this only seems to work for arrays.
646 Dygraph
.clone
= function(o
) {
647 // TODO(danvk): figure out how MochiKit's version works
649 for (var i
= 0; i
< o
.length
; i
++) {
650 if (Dygraph
.isArrayLike(o
[i
])) {
651 r
.push(Dygraph
.clone(o
[i
]));
661 * Create a new canvas element. This is more complex than a simple
662 * document.createElement("canvas") because of IE and excanvas.
664 Dygraph
.createCanvas
= function() {
665 var canvas
= document
.createElement("canvas");
667 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
668 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
669 canvas
= G_vmlCanvasManager
.initElement(canvas
);
677 * Checks whether the user is on an Android browser.
678 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
680 Dygraph
.isAndroid
= function() {
681 return (/Android/).test(navigator
.userAgent
);
686 * Call a function N times at a given interval, then call a cleanup function
687 * once. repeat_fn is called once immediately, then (times - 1) times
688 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
689 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
690 * (from 0 to times-1) as an argument.
691 * @param times {number} The number of times to call repeat_fn
692 * @param every_ms {number} Milliseconds between calls
693 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
696 Dygraph
.repeatAndCleanup
= function(repeat_fn
, times
, every_ms
, cleanup_fn
) {
698 var start_time
= new Date().getTime();
706 if (count
>= times
) return;
707 var target_time
= start_time
+ (1 + count
) * every_ms
;
708 setTimeout(function() {
711 if (count
>= times
- 1) {
716 }, target_time
- new Date().getTime());
717 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
723 * This function will scan the option list and determine if they
724 * require us to recalculate the pixel positions of each point.
725 * @param { List } a list of options to check.
726 * @return { Boolean } true if the graph needs new points else false.
728 Dygraph
.isPixelChangingOptionList
= function(labels
, attrs
) {
729 // A whitelist of options that do not change pixel positions.
730 var pixelSafeOptions
= {
731 'annotationClickHandler': true,
732 'annotationDblClickHandler': true,
733 'annotationMouseOutHandler': true,
734 'annotationMouseOverHandler': true,
735 'axisLabelColor': true,
736 'axisLineColor': true,
737 'axisLineWidth': true,
738 'clickCallback': true,
739 'digitsAfterDecimal': true,
740 'drawCallback': true,
741 'drawHighlightPointCallback': true,
743 'drawPointCallback': true,
747 'gridLineColor': true,
748 'gridLineWidth': true,
749 'hideOverlayOnMouseOut': true,
750 'highlightCallback': true,
751 'highlightCircleSize': true,
752 'interactionModel': true,
753 'isZoomedIgnoreProgrammaticZoom': true,
755 'labelsDivStyles': true,
756 'labelsDivWidth': true,
759 'labelsSeparateLines': true,
760 'labelsShowZeroValues': true,
762 'maxNumberWidth': true,
763 'panEdgeFraction': true,
764 'pixelsPerYLabel': true,
765 'pointClickCallback': true,
767 'rangeSelectorPlotFillColor': true,
768 'rangeSelectorPlotStrokeColor': true,
769 'showLabelsOnHighlight': true,
773 'underlayCallback': true,
774 'unhighlightCallback': true,
775 'xAxisLabelFormatter': true,
777 'xValueFormatter': true,
778 'yAxisLabelFormatter': true,
779 'yValueFormatter': true,
783 // Assume that we do not require new points.
784 // This will change to true if we actually do need new points.
785 var requiresNewPoints
= false;
787 // Create a dictionary of series names for faster lookup.
788 // If there are no labels, then the dictionary stays empty.
789 var seriesNamesDictionary
= { };
791 for (var i
= 1; i
< labels
.length
; i
++) {
792 seriesNamesDictionary
[labels
[i
]] = true;
796 // Iterate through the list of updated options.
797 for (var property
in attrs
) {
798 // Break early if we already know we need new points from a previous option.
799 if (requiresNewPoints
) {
802 if (attrs
.hasOwnProperty(property
)) {
803 // Find out of this field is actually a series specific options list.
804 if (seriesNamesDictionary
[property
]) {
805 // This property value is a list of options for this series.
806 // If any of these sub properties are not pixel safe, set the flag.
807 for (var subProperty
in attrs
[property
]) {
808 // Break early if we already know we need new points from a previous option.
809 if (requiresNewPoints
) {
812 if (attrs
[property
].hasOwnProperty(subProperty
) && !pixelSafeOptions
[subProperty
]) {
813 requiresNewPoints
= true;
816 // If this was not a series specific option list, check if its a pixel changing property.
817 } else if (!pixelSafeOptions
[property
]) {
818 requiresNewPoints
= true;
823 return requiresNewPoints
;
827 * Compares two arrays to see if they are equal. If either parameter is not an
828 * array it will return false. Does a shallow compare
829 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
830 * @param array1 first array
831 * @param array2 second array
832 * @return True if both parameters are arrays, and contents are equal.
834 Dygraph
.compareArrays
= function(array1
, array2
) {
835 if (!Dygraph
.isArrayLike(array1
) || !Dygraph
.isArrayLike(array2
)) {
838 if (array1
.length
!== array2
.length
) {
841 for (var i
= 0; i
< array1
.length
; i
++) {
842 if (array1
[i
] !== array2
[i
]) {
850 * ctx: the canvas context
851 * sides: the number of sides in the shape.
852 * radius: the radius of the image.
853 * cx: center x coordate
854 * cy: center y coordinate
855 * rotationRadians: the shift of the initial angle, in radians.
856 * delta: the angle shift for each line. If missing, creates a regular
859 Dygraph
.regularShape_
= function(
860 ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
) {
861 rotationRadians
= rotationRadians
? rotationRadians
: 0;
862 delta
= delta
? delta
: Math
.PI
* 2 / sides
;
866 var initialAngle
= rotationRadians
;
867 var angle
= initialAngle
;
869 var computeCoordinates
= function() {
870 var x
= cx
+ (Math
.sin(angle
) * radius
);
871 var y
= cy
+ (-Math
.cos(angle
) * radius
);
875 var initialCoordinates
= computeCoordinates();
876 var x
= initialCoordinates
[0];
877 var y
= initialCoordinates
[1];
880 for (var idx
= 0; idx
< sides
; idx
++) {
881 angle
= (idx
== sides
- 1) ? initialAngle
: (angle
+ delta
);
882 var coords
= computeCoordinates();
883 ctx
.lineTo(coords
[0], coords
[1]);
889 Dygraph
.shapeFunction_
= function(sides
, rotationRadians
, delta
) {
890 return function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
891 ctx
.strokeStyle
= color
;
892 ctx
.fillStyle
= "white";
893 Dygraph
.regularShape_(ctx
, sides
, radius
, cx
, cy
, rotationRadians
, delta
);
897 Dygraph
.DrawPolygon_
= function(sides
, rotationRadians
, ctx
, cx
, cy
, color
, radius
, delta
) {
898 new Dygraph
.RegularShape_(sides
, rotationRadians
, delta
).draw(ctx
, cx
, cy
, radius
);
902 DEFAULT
: function(g
, name
, ctx
, canvasx
, canvasy
, color
, radius
) {
904 ctx
.fillStyle
= color
;
905 ctx
.arc(canvasx
, canvasy
, radius
, 0, 2 * Math
.PI
, false);
908 TRIANGLE
: Dygraph
.shapeFunction_(3),
909 SQUARE
: Dygraph
.shapeFunction_(4, Math
.PI
/ 4),
910 DIAMOND
: Dygraph
.shapeFunction_(4),
911 PENTAGON
: Dygraph
.shapeFunction_(5),
912 HEXAGON
: Dygraph
.shapeFunction_(6),
913 CIRCLE
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
915 ctx
.strokeStyle
= color
;
916 ctx
.fillStyle
= "white";
917 ctx
.arc(cx
, cy
, radius
, 0, 2 * Math
.PI
, false);
921 STAR
: Dygraph
.shapeFunction_(5, 0, 4 * Math
.PI
/ 5),
922 PLUS
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
923 ctx
.strokeStyle
= color
;
926 ctx
.moveTo(cx
+ radius
, cy
);
927 ctx
.lineTo(cx
- radius
, cy
);
932 ctx
.moveTo(cx
, cy
+ radius
);
933 ctx
.lineTo(cx
, cy
- radius
);
937 EX
: function(g
, name
, ctx
, cx
, cy
, color
, radius
) {
938 ctx
.strokeStyle
= color
;
941 ctx
.moveTo(cx
+ radius
, cy
+ radius
);
942 ctx
.lineTo(cx
- radius
, cy
- radius
);
947 ctx
.moveTo(cx
+ radius
, cy
- radius
);
948 ctx
.lineTo(cx
- radius
, cy
+ radius
);