custom circles, first part.
[dygraphs.git] / dygraph-utils.js
1 /**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
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.
12 */
13
14 /*jshint globalstrict: true */
15 /*global Dygraph:false, G_vmlCanvasManager:false, Node:false, printStackTrace: false */
16 "use strict";
17
18 Dygraph.LOG_SCALE = 10;
19 Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
20
21 /** @private */
22 Dygraph.log10 = function(x) {
23 return Math.log(x) / Dygraph.LN_TEN;
24 };
25
26 // Various logging levels.
27 Dygraph.DEBUG = 1;
28 Dygraph.INFO = 2;
29 Dygraph.WARNING = 3;
30 Dygraph.ERROR = 3;
31
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;
37
38 /**
39 * @private
40 * Log an error on the JS console at the given severity.
41 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
42 * @param { String } The message to log.
43 */
44 Dygraph.log = function(severity, message) {
45 var st;
46 if (typeof(printStackTrace) != 'undefined') {
47 // Remove uninteresting bits: logging functions and paths.
48 st = printStackTrace({guess:false});
49 while (st[0].indexOf("stacktrace") != -1) {
50 st.splice(0, 1);
51 }
52
53 st.splice(0, 2);
54 for (var i = 0; i < st.length; i++) {
55 st[i] = st[i].replace(/\([^)]*\/(.*)\)/, '@$1')
56 .replace(/\@.*\/([^\/]*)/, '@$1')
57 .replace('[object Object].', '');
58 }
59 var top_msg = st.splice(0, 1)[0];
60 message += ' (' + top_msg.replace(/^.*@ ?/, '') + ')';
61 }
62
63 if (typeof(console) != 'undefined') {
64 switch (severity) {
65 case Dygraph.DEBUG:
66 console.debug('dygraphs: ' + message);
67 break;
68 case Dygraph.INFO:
69 console.info('dygraphs: ' + message);
70 break;
71 case Dygraph.WARNING:
72 console.warn('dygraphs: ' + message);
73 break;
74 case Dygraph.ERROR:
75 console.error('dygraphs: ' + message);
76 break;
77 }
78 }
79
80 if (Dygraph.LOG_STACK_TRACES) {
81 console.log(st.join('\n'));
82 }
83 };
84
85 /** @private */
86 Dygraph.info = function(message) {
87 Dygraph.log(Dygraph.INFO, message);
88 };
89 /** @private */
90 Dygraph.prototype.info = Dygraph.info;
91
92 /** @private */
93 Dygraph.warn = function(message) {
94 Dygraph.log(Dygraph.WARNING, message);
95 };
96 /** @private */
97 Dygraph.prototype.warn = Dygraph.warn;
98
99 /** @private */
100 Dygraph.error = function(message) {
101 Dygraph.log(Dygraph.ERROR, message);
102 };
103 /** @private */
104 Dygraph.prototype.error = Dygraph.error;
105
106 /**
107 * @private
108 * Return the 2d context for a dygraph canvas.
109 *
110 * This method is only exposed for the sake of replacing the function in
111 * automated tests, e.g.
112 *
113 * var oldFunc = Dygraph.getContext();
114 * Dygraph.getContext = function(canvas) {
115 * var realContext = oldFunc(canvas);
116 * return new Proxy(realContext);
117 * };
118 */
119 Dygraph.getContext = function(canvas) {
120 return canvas.getContext("2d");
121 };
122
123 /**
124 * @private
125 * Add an event handler. This smooths a difference between IE and the rest of
126 * the world.
127 * @param { DOM element } elem The element to add the event to.
128 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
129 * @param { Function } fn The function to call on the event. The function takes
130 * one parameter: the event object.
131 */
132 Dygraph.addEvent = function addEvent(elem, type, fn) {
133 if (elem.addEventListener) {
134 elem.addEventListener(type, fn, false);
135 } else {
136 elem[type+fn] = function(){fn(window.event);};
137 elem.attachEvent('on'+type, elem[type+fn]);
138 }
139 };
140
141 /**
142 * @private
143 * Remove an event handler. This smooths a difference between IE and the rest of
144 * the world.
145 * @param { DOM element } elem The element to add the event to.
146 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
147 * @param { Function } fn The function to call on the event. The function takes
148 * one parameter: the event object.
149 */
150 Dygraph.removeEvent = function addEvent(elem, type, fn) {
151 if (elem.removeEventListener) {
152 elem.removeEventListener(type, fn, false);
153 } else {
154 elem.detachEvent('on'+type, elem[type+fn]);
155 elem[type+fn] = null;
156 }
157 };
158
159 /**
160 * @private
161 * Cancels further processing of an event. This is useful to prevent default
162 * browser actions, e.g. highlighting text on a double-click.
163 * Based on the article at
164 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
165 * @param { Event } e The event whose normal behavior should be canceled.
166 */
167 Dygraph.cancelEvent = function(e) {
168 e = e ? e : window.event;
169 if (e.stopPropagation) {
170 e.stopPropagation();
171 }
172 if (e.preventDefault) {
173 e.preventDefault();
174 }
175 e.cancelBubble = true;
176 e.cancel = true;
177 e.returnValue = false;
178 return false;
179 };
180
181 /**
182 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
183 * is used to generate default series colors which are evenly spaced on the
184 * color wheel.
185 * @param { Number } hue Range is 0.0-1.0.
186 * @param { Number } saturation Range is 0.0-1.0.
187 * @param { Number } value Range is 0.0-1.0.
188 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
189 * @private
190 */
191 Dygraph.hsvToRGB = function (hue, saturation, value) {
192 var red;
193 var green;
194 var blue;
195 if (saturation === 0) {
196 red = value;
197 green = value;
198 blue = value;
199 } else {
200 var i = Math.floor(hue * 6);
201 var f = (hue * 6) - i;
202 var p = value * (1 - saturation);
203 var q = value * (1 - (saturation * f));
204 var t = value * (1 - (saturation * (1 - f)));
205 switch (i) {
206 case 1: red = q; green = value; blue = p; break;
207 case 2: red = p; green = value; blue = t; break;
208 case 3: red = p; green = q; blue = value; break;
209 case 4: red = t; green = p; blue = value; break;
210 case 5: red = value; green = p; blue = q; break;
211 case 6: // fall through
212 case 0: red = value; green = t; blue = p; break;
213 }
214 }
215 red = Math.floor(255 * red + 0.5);
216 green = Math.floor(255 * green + 0.5);
217 blue = Math.floor(255 * blue + 0.5);
218 return 'rgb(' + red + ',' + green + ',' + blue + ')';
219 };
220
221 // The following functions are from quirksmode.org with a modification for Safari from
222 // http://blog.firetree.net/2005/07/04/javascript-find-position/
223 // http://www.quirksmode.org/js/findpos.html
224 // ... and modifications to support scrolling divs.
225
226 /**
227 * Find the x-coordinate of the supplied object relative to the left side
228 * of the page.
229 * @private
230 */
231 Dygraph.findPosX = function(obj) {
232 var curleft = 0;
233 if(obj.offsetParent) {
234 var copyObj = obj;
235 while(1) {
236 curleft += copyObj.offsetLeft;
237 if(!copyObj.offsetParent) {
238 break;
239 }
240 copyObj = copyObj.offsetParent;
241 }
242 } else if(obj.x) {
243 curleft += obj.x;
244 }
245 // This handles the case where the object is inside a scrolled div.
246 while(obj && obj != document.body) {
247 curleft -= obj.scrollLeft;
248 obj = obj.parentNode;
249 }
250 return curleft;
251 };
252
253 /**
254 * Find the y-coordinate of the supplied object relative to the top of the
255 * page.
256 * @private
257 */
258 Dygraph.findPosY = function(obj) {
259 var curtop = 0;
260 if(obj.offsetParent) {
261 var copyObj = obj;
262 while(1) {
263 curtop += copyObj.offsetTop;
264 if(!copyObj.offsetParent) {
265 break;
266 }
267 copyObj = copyObj.offsetParent;
268 }
269 } else if(obj.y) {
270 curtop += obj.y;
271 }
272 // This handles the case where the object is inside a scrolled div.
273 while(obj && obj != document.body) {
274 curtop -= obj.scrollTop;
275 obj = obj.parentNode;
276 }
277 return curtop;
278 };
279
280 /**
281 * @private
282 * Returns the x-coordinate of the event in a coordinate system where the
283 * top-left corner of the page (not the window) is (0,0).
284 * Taken from MochiKit.Signal
285 */
286 Dygraph.pageX = function(e) {
287 if (e.pageX) {
288 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
289 } else {
290 var de = document;
291 var b = document.body;
292 return e.clientX +
293 (de.scrollLeft || b.scrollLeft) -
294 (de.clientLeft || 0);
295 }
296 };
297
298 /**
299 * @private
300 * Returns the y-coordinate of the event in a coordinate system where the
301 * top-left corner of the page (not the window) is (0,0).
302 * Taken from MochiKit.Signal
303 */
304 Dygraph.pageY = function(e) {
305 if (e.pageY) {
306 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
307 } else {
308 var de = document;
309 var b = document.body;
310 return e.clientY +
311 (de.scrollTop || b.scrollTop) -
312 (de.clientTop || 0);
313 }
314 };
315
316 /**
317 * @private
318 * @param { Number } x The number to consider.
319 * @return { Boolean } Whether the number is zero or NaN.
320 */
321 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
322 // TODO(danvk): determine when else this returns false (e.g. for undefined or null)
323 Dygraph.isOK = function(x) {
324 return x && !isNaN(x);
325 };
326
327 /**
328 * Number formatting function which mimicks the behavior of %g in printf, i.e.
329 * either exponential or fixed format (without trailing 0s) is used depending on
330 * the length of the generated string. The advantage of this format is that
331 * there is a predictable upper bound on the resulting string length,
332 * significant figures are not dropped, and normal numbers are not displayed in
333 * exponential notation.
334 *
335 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
336 * It creates strings which are too long for absolute values between 10^-4 and
337 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
338 * output examples.
339 *
340 * @param {Number} x The number to format
341 * @param {Number} opt_precision The precision to use, default 2.
342 * @return {String} A string formatted like %g in printf. The max generated
343 * string length should be precision + 6 (e.g 1.123e+300).
344 */
345 Dygraph.floatFormat = function(x, opt_precision) {
346 // Avoid invalid precision values; [1, 21] is the valid range.
347 var p = Math.min(Math.max(1, opt_precision || 2), 21);
348
349 // This is deceptively simple. The actual algorithm comes from:
350 //
351 // Max allowed length = p + 4
352 // where 4 comes from 'e+n' and '.'.
353 //
354 // Length of fixed format = 2 + y + p
355 // where 2 comes from '0.' and y = # of leading zeroes.
356 //
357 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
358 // 1.0e-3.
359 //
360 // Since the behavior of toPrecision() is identical for larger numbers, we
361 // don't have to worry about the other bound.
362 //
363 // Finally, the argument for toExponential() is the number of trailing digits,
364 // so we take off 1 for the value before the '.'.
365 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
366 x.toExponential(p - 1) : x.toPrecision(p);
367 };
368
369 /**
370 * @private
371 * Converts '9' to '09' (useful for dates)
372 */
373 Dygraph.zeropad = function(x) {
374 if (x < 10) return "0" + x; else return "" + x;
375 };
376
377 /**
378 * Return a string version of the hours, minutes and seconds portion of a date.
379 * @param {Number} date The JavaScript date (ms since epoch)
380 * @return {String} A time of the form "HH:MM:SS"
381 * @private
382 */
383 Dygraph.hmsString_ = function(date) {
384 var zeropad = Dygraph.zeropad;
385 var d = new Date(date);
386 if (d.getSeconds()) {
387 return zeropad(d.getHours()) + ":" +
388 zeropad(d.getMinutes()) + ":" +
389 zeropad(d.getSeconds());
390 } else {
391 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
392 }
393 };
394
395 /**
396 * Round a number to the specified number of digits past the decimal point.
397 * @param {Number} num The number to round
398 * @param {Number} places The number of decimals to which to round
399 * @return {Number} The rounded number
400 * @private
401 */
402 Dygraph.round_ = function(num, places) {
403 var shift = Math.pow(10, places);
404 return Math.round(num * shift)/shift;
405 };
406
407 /**
408 * @private
409 * Implementation of binary search over an array.
410 * Currently does not work when val is outside the range of arry's values.
411 * @param { Integer } val the value to search for
412 * @param { Integer[] } arry is the value over which to search
413 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
414 * If abs < 0, find the highest entry less than val.
415 * if abs == 0, find the entry that equals val.
416 * @param { Integer } [low] The first index in arry to consider (optional)
417 * @param { Integer } [high] The last index in arry to consider (optional)
418 */
419 Dygraph.binarySearch = function(val, arry, abs, low, high) {
420 if (low === null || low === undefined ||
421 high === null || high === undefined) {
422 low = 0;
423 high = arry.length - 1;
424 }
425 if (low > high) {
426 return -1;
427 }
428 if (abs === null || abs === undefined) {
429 abs = 0;
430 }
431 var validIndex = function(idx) {
432 return idx >= 0 && idx < arry.length;
433 };
434 var mid = parseInt((low + high) / 2, 10);
435 var element = arry[mid];
436 if (element == val) {
437 return mid;
438 }
439
440 var idx;
441 if (element > val) {
442 if (abs > 0) {
443 // Accept if element > val, but also if prior element < val.
444 idx = mid - 1;
445 if (validIndex(idx) && arry[idx] < val) {
446 return mid;
447 }
448 }
449 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
450 }
451 if (element < val) {
452 if (abs < 0) {
453 // Accept if element < val, but also if prior element > val.
454 idx = mid + 1;
455 if (validIndex(idx) && arry[idx] > val) {
456 return mid;
457 }
458 }
459 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
460 }
461 };
462
463 /**
464 * @private
465 * Parses a date, returning the number of milliseconds since epoch. This can be
466 * passed in as an xValueParser in the Dygraph constructor.
467 * TODO(danvk): enumerate formats that this understands.
468 * @param {String} A date in YYYYMMDD format.
469 * @return {Number} Milliseconds since epoch.
470 */
471 Dygraph.dateParser = function(dateStr) {
472 var dateStrSlashed;
473 var d;
474
475 // Let the system try the format first.
476 d = Dygraph.dateStrToMillis(dateStr);
477 if (d && !isNaN(d)) return d;
478
479 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
480 dateStrSlashed = dateStr.replace("-", "/", "g");
481 while (dateStrSlashed.search("-") != -1) {
482 dateStrSlashed = dateStrSlashed.replace("-", "/");
483 }
484 d = Dygraph.dateStrToMillis(dateStrSlashed);
485 } else if (dateStr.length == 8) { // e.g. '20090712'
486 // TODO(danvk): remove support for this format. It's confusing.
487 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
488 dateStr.substr(6,2);
489 d = Dygraph.dateStrToMillis(dateStrSlashed);
490 } else {
491 // Any format that Date.parse will accept, e.g. "2009/07/12" or
492 // "2009/07/12 12:34:56"
493 d = Dygraph.dateStrToMillis(dateStr);
494 }
495
496 if (!d || isNaN(d)) {
497 Dygraph.error("Couldn't parse " + dateStr + " as a date");
498 }
499 return d;
500 };
501
502 /**
503 * @private
504 * This is identical to JavaScript's built-in Date.parse() method, except that
505 * it doesn't get replaced with an incompatible method by aggressive JS
506 * libraries like MooTools or Joomla.
507 * @param { String } str The date string, e.g. "2011/05/06"
508 * @return { Integer } millis since epoch
509 */
510 Dygraph.dateStrToMillis = function(str) {
511 return new Date(str).getTime();
512 };
513
514 // These functions are all based on MochiKit.
515 /**
516 * Copies all the properties from o to self.
517 *
518 * @private
519 */
520 Dygraph.update = function (self, o) {
521 if (typeof(o) != 'undefined' && o !== null) {
522 for (var k in o) {
523 if (o.hasOwnProperty(k)) {
524 self[k] = o[k];
525 }
526 }
527 }
528 return self;
529 };
530
531 /**
532 * Copies all the properties from o to self.
533 *
534 * @private
535 */
536 Dygraph.updateDeep = function (self, o) {
537 // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
538 function isNode(o) {
539 return (
540 typeof Node === "object" ? o instanceof Node :
541 typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
542 );
543 }
544
545 if (typeof(o) != 'undefined' && o !== null) {
546 for (var k in o) {
547 if (o.hasOwnProperty(k)) {
548 if (o[k] === null) {
549 self[k] = null;
550 } else if (Dygraph.isArrayLike(o[k])) {
551 self[k] = o[k].slice();
552 } else if (isNode(o[k])) {
553 // DOM objects are shallowly-copied.
554 self[k] = o[k];
555 } else if (typeof(o[k]) == 'object') {
556 if (typeof(self[k]) != 'object') {
557 self[k] = {};
558 }
559 Dygraph.updateDeep(self[k], o[k]);
560 } else {
561 self[k] = o[k];
562 }
563 }
564 }
565 }
566 return self;
567 };
568
569 /**
570 * @private
571 */
572 Dygraph.isArrayLike = function (o) {
573 var typ = typeof(o);
574 if (
575 (typ != 'object' && !(typ == 'function' &&
576 typeof(o.item) == 'function')) ||
577 o === null ||
578 typeof(o.length) != 'number' ||
579 o.nodeType === 3
580 ) {
581 return false;
582 }
583 return true;
584 };
585
586 /**
587 * @private
588 */
589 Dygraph.isDateLike = function (o) {
590 if (typeof(o) != "object" || o === null ||
591 typeof(o.getTime) != 'function') {
592 return false;
593 }
594 return true;
595 };
596
597 /**
598 * Note: this only seems to work for arrays.
599 * @private
600 */
601 Dygraph.clone = function(o) {
602 // TODO(danvk): figure out how MochiKit's version works
603 var r = [];
604 for (var i = 0; i < o.length; i++) {
605 if (Dygraph.isArrayLike(o[i])) {
606 r.push(Dygraph.clone(o[i]));
607 } else {
608 r.push(o[i]);
609 }
610 }
611 return r;
612 };
613
614 /**
615 * @private
616 * Create a new canvas element. This is more complex than a simple
617 * document.createElement("canvas") because of IE and excanvas.
618 */
619 Dygraph.createCanvas = function() {
620 var canvas = document.createElement("canvas");
621
622 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
623 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
624 canvas = G_vmlCanvasManager.initElement(canvas);
625 }
626
627 return canvas;
628 };
629
630 /**
631 * @private
632 * Checks whether the user is on an Android browser.
633 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
634 */
635 Dygraph.isAndroid = function() {
636 return (/Android/).test(navigator.userAgent);
637 };
638
639 /**
640 * @private
641 * Call a function N times at a given interval, then call a cleanup function
642 * once. repeat_fn is called once immediately, then (times - 1) times
643 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
644 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
645 * (from 0 to times-1) as an argument.
646 * @param times {number} The number of times to call repeat_fn
647 * @param every_ms {number} Milliseconds between calls
648 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
649 * @private
650 */
651 Dygraph.repeatAndCleanup = function(repeat_fn, times, every_ms, cleanup_fn) {
652 var count = 0;
653 var start_time = new Date().getTime();
654 repeat_fn(count);
655 if (times == 1) {
656 cleanup_fn();
657 return;
658 }
659
660 (function loop() {
661 if (count >= times) return;
662 var target_time = start_time + (1 + count) * every_ms;
663 setTimeout(function() {
664 count++;
665 repeat_fn(count);
666 if (count >= times - 1) {
667 cleanup_fn();
668 } else {
669 loop();
670 }
671 }, target_time - new Date().getTime());
672 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
673 })();
674 };
675
676 /**
677 * @private
678 * This function will scan the option list and determine if they
679 * require us to recalculate the pixel positions of each point.
680 * @param { List } a list of options to check.
681 * @return { Boolean } true if the graph needs new points else false.
682 */
683 Dygraph.isPixelChangingOptionList = function(labels, attrs) {
684 // A whitelist of options that do not change pixel positions.
685 var pixelSafeOptions = {
686 'annotationClickHandler': true,
687 'annotationDblClickHandler': true,
688 'annotationMouseOutHandler': true,
689 'annotationMouseOverHandler': true,
690 'axisLabelColor': true,
691 'axisLineColor': true,
692 'axisLineWidth': true,
693 'clickCallback': true,
694 'digitsAfterDecimal': true,
695 'drawCallback': true,
696 'drawHighlightCallback': true,
697 'drawPoints': true,
698 'drawPointCallback': true,
699 'drawXGrid': true,
700 'drawYGrid': true,
701 'fillAlpha': true,
702 'gridLineColor': true,
703 'gridLineWidth': true,
704 'hideOverlayOnMouseOut': true,
705 'highlightCallback': true,
706 'highlightCircleSize': true,
707 'interactionModel': true,
708 'isZoomedIgnoreProgrammaticZoom': true,
709 'labelsDiv': true,
710 'labelsDivStyles': true,
711 'labelsDivWidth': true,
712 'labelsKMB': true,
713 'labelsKMG2': true,
714 'labelsSeparateLines': true,
715 'labelsShowZeroValues': true,
716 'legend': true,
717 'maxNumberWidth': true,
718 'panEdgeFraction': true,
719 'pixelsPerYLabel': true,
720 'pointClickCallback': true,
721 'pointSize': true,
722 'rangeSelectorPlotFillColor': true,
723 'rangeSelectorPlotStrokeColor': true,
724 'showLabelsOnHighlight': true,
725 'showRoller': true,
726 'sigFigs': true,
727 'strokeWidth': true,
728 'underlayCallback': true,
729 'unhighlightCallback': true,
730 'xAxisLabelFormatter': true,
731 'xTicker': true,
732 'xValueFormatter': true,
733 'yAxisLabelFormatter': true,
734 'yValueFormatter': true,
735 'zoomCallback': true
736 };
737
738 // Assume that we do not require new points.
739 // This will change to true if we actually do need new points.
740 var requiresNewPoints = false;
741
742 // Create a dictionary of series names for faster lookup.
743 // If there are no labels, then the dictionary stays empty.
744 var seriesNamesDictionary = { };
745 if (labels) {
746 for (var i = 1; i < labels.length; i++) {
747 seriesNamesDictionary[labels[i]] = true;
748 }
749 }
750
751 // Iterate through the list of updated options.
752 for (var property in attrs) {
753 // Break early if we already know we need new points from a previous option.
754 if (requiresNewPoints) {
755 break;
756 }
757 if (attrs.hasOwnProperty(property)) {
758 // Find out of this field is actually a series specific options list.
759 if (seriesNamesDictionary[property]) {
760 // This property value is a list of options for this series.
761 // If any of these sub properties are not pixel safe, set the flag.
762 for (var subProperty in attrs[property]) {
763 // Break early if we already know we need new points from a previous option.
764 if (requiresNewPoints) {
765 break;
766 }
767 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
768 requiresNewPoints = true;
769 }
770 }
771 // If this was not a series specific option list, check if its a pixel changing property.
772 } else if (!pixelSafeOptions[property]) {
773 requiresNewPoints = true;
774 }
775 }
776 }
777
778 return requiresNewPoints;
779 };
780
781
782 Dygraph.RegularConvex = function(sides, rotation) {
783 this.sides = sides;
784 this.rotation = rotation ? rotation : 0;
785 this.delta = Math.PI * 2 / sides;
786 }
787
788 Dygraph.RegularConvex.prototype.draw = function(ctx, cx, cy, radius, angleAdjustment) {
789 ctx.beginPath();
790 var first = true;
791 if (!angleAdjustment) angleAdjustment = 0;
792 var angle = this.rotation + angleAdjustment;
793
794 var x = cx + (Math.sin(angle) * radius);
795 var y = cy + (-Math.cos(angle) * radius);
796 ctx.moveTo(x, y);
797
798 for (var idx = 0; idx < this.sides; idx++) {
799 angle = (idx == this.sides - 1) ? this.rotation : (angle + this.delta);
800 var x = cx + (Math.sin(angle) * radius);
801 var y = cy + (-Math.cos(angle) * radius);
802 ctx.lineTo(x, y);
803 }
804 ctx.stroke();
805 ctx.closePath();
806 }
807
808 Dygraph.DrawPolygon_ = function(sides, rotation, ctx, cx, cy, color, radius, angleAdjustment) {
809 ctx.lineWidth = 1;
810 ctx.strokeStyle = color;
811 new Dygraph.RegularConvex(sides, rotation).draw(ctx, cx, cy, radius, angleAdjustment);
812 }
813
814 Dygraph.Circles = {
815 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
816 ctx.beginPath();
817 ctx.fillStyle = color;
818 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
819 ctx.fill();
820 },
821 TRIANGLE : function(g, name, ctx, cx, cy, color, radius) {
822 Dygraph.DrawPolygon_(3, Math.PI / 3, ctx, cx, cy, color, radius);
823 },
824 SQUARE : function(g, name, ctx, cx, cy, color, radius) {
825 Dygraph.DrawPolygon_(4, Math.PI / 4, ctx, cx, cy, color, radius);
826 },
827 DIAMOND : function(g, name, ctx, cx, cy, color, radius) {
828 Dygraph.DrawPolygon_(4, Math.PI / 4, ctx, cx, cy, color, radius, Math.PI / 8);
829 },
830 PENTAGON : function(g, name, ctx, cx, cy, color, radius) {
831 Dygraph.DrawPolygon_(5, Math.PI / 5, ctx, cx, cy, color, radius);
832 },
833 HEXAGON : function(g, name, ctx, cx, cy, color, radius) {
834 Dygraph.DrawPolygon_(6, Math.PI / 6, ctx, cx, cy, color, radius);
835 },
836 CIRCLE : function(g, name, ctx, cx, cy, color, radius) {
837 ctx.beginPath();
838 ctx.lineStyle = color;
839 ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false);
840 ctx.fill();
841 },
842 STAR : function(g, name, ctx, cx, cy, color, radius) {
843 Dygraph.DrawPolygon_(5, 2 * Math.PI / 5, ctx, cx, cy, color, radius);
844 }
845 // TODO: plus, x.
846 };