Add JSHint and make dygraphs pass its checks.
[dygraphs.git] / dygraph-canvas.js
1 /**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
11 * In particular, support for:
12 * - grid overlays
13 * - error bars
14 * - dygraphs attribute system
15 */
16
17 /**
18 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
19 * a canvas. It's based on PlotKit.CanvasRenderer.
20 * @param {Object} element The canvas to attach to
21 * @param {Object} elementContext The 2d context of the canvas (injected so it
22 * can be mocked for testing.)
23 * @param {Layout} layout The DygraphLayout object for this graph.
24 * @constructor
25 */
26
27 /*jshint globalstrict: true */
28 /*global Dygraph:false,RGBColor:false */
29 "use strict";
30
31 var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
32 this.dygraph_ = dygraph;
33
34 this.layout = layout;
35 this.element = element;
36 this.elementContext = elementContext;
37 this.container = this.element.parentNode;
38
39 this.height = this.element.height;
40 this.width = this.element.width;
41
42 // --- check whether everything is ok before we return
43 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
44 throw "Canvas is not supported.";
45
46 // internal state
47 this.xlabels = [];
48 this.ylabels = [];
49 this.annotations = [];
50 this.chartLabels = {};
51
52 this.area = layout.getPlotArea();
53 this.container.style.position = "relative";
54 this.container.style.width = this.width + "px";
55
56 // Set up a clipping area for the canvas (and the interaction canvas).
57 // This ensures that we don't overdraw.
58 if (this.dygraph_.isUsingExcanvas_) {
59 this._createIEClipArea();
60 } else {
61 // on Android 3 and 4, setting a clipping area on a canvas prevents it from
62 // displaying anything.
63 if (!Dygraph.isAndroid()) {
64 var ctx = this.dygraph_.canvas_ctx_;
65 ctx.beginPath();
66 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
67 ctx.clip();
68
69 ctx = this.dygraph_.hidden_ctx_;
70 ctx.beginPath();
71 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
72 ctx.clip();
73 }
74 }
75 };
76
77 DygraphCanvasRenderer.prototype.attr_ = function(x) {
78 return this.dygraph_.attr_(x);
79 };
80
81 DygraphCanvasRenderer.prototype.clear = function() {
82 var context;
83 if (this.isIE) {
84 // VML takes a while to start up, so we just poll every this.IEDelay
85 try {
86 if (this.clearDelay) {
87 this.clearDelay.cancel();
88 this.clearDelay = null;
89 }
90 context = this.elementContext;
91 }
92 catch (e) {
93 // TODO(danvk): this is broken, since MochiKit.Async is gone.
94 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
95 // this.clearDelay.addCallback(bind(this.clear, this));
96 return;
97 }
98 }
99
100 context = this.elementContext;
101 context.clearRect(0, 0, this.width, this.height);
102
103 function removeArray(ary) {
104 for (var i = 0; i < ary.length; i++) {
105 var el = ary[i];
106 if (el.parentNode) el.parentNode.removeChild(el);
107 }
108 }
109
110 removeArray(this.xlabels);
111 removeArray(this.ylabels);
112 removeArray(this.annotations);
113
114 for (var k in this.chartLabels) {
115 if (!this.chartLabels.hasOwnProperty(k)) continue;
116 var el = this.chartLabels[k];
117 if (el.parentNode) el.parentNode.removeChild(el);
118 }
119 this.xlabels = [];
120 this.ylabels = [];
121 this.annotations = [];
122 this.chartLabels = {};
123 };
124
125
126 DygraphCanvasRenderer.isSupported = function(canvasName) {
127 var canvas = null;
128 try {
129 if (typeof(canvasName) == 'undefined' || canvasName === null) {
130 canvas = document.createElement("canvas");
131 } else {
132 canvas = canvasName;
133 }
134 canvas.getContext("2d");
135 }
136 catch (e) {
137 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
138 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
139 if ((!ie) || (ie[1] < 6) || (opera))
140 return false;
141 return true;
142 }
143 return true;
144 };
145
146 /**
147 * @param { [String] } colors Array of color strings. Should have one entry for
148 * each series to be rendered.
149 */
150 DygraphCanvasRenderer.prototype.setColors = function(colors) {
151 this.colorScheme_ = colors;
152 };
153
154 /**
155 * Draw an X/Y grid on top of the existing plot
156 */
157 DygraphCanvasRenderer.prototype.render = function() {
158 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
159 // half-integers. This prevents them from drawing in two rows/cols.
160 var ctx = this.elementContext;
161 function halfUp(x) { return Math.round(x) + 0.5; }
162 function halfDown(y){ return Math.round(y) - 0.5; }
163
164 if (this.attr_('underlayCallback')) {
165 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
166 // users who expect a deprecated form of this callback.
167 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
168 }
169
170 var x, y, i, ticks;
171 if (this.attr_('drawYGrid')) {
172 ticks = this.layout.yticks;
173 // TODO(konigsberg): I don't think these calls to save() have a corresponding restore().
174 ctx.save();
175 ctx.strokeStyle = this.attr_('gridLineColor');
176 ctx.lineWidth = this.attr_('gridLineWidth');
177 for (i = 0; i < ticks.length; i++) {
178 // TODO(danvk): allow secondary axes to draw a grid, too.
179 if (ticks[i][0] !== 0) continue;
180 x = halfUp(this.area.x);
181 y = halfDown(this.area.y + ticks[i][1] * this.area.h);
182 ctx.beginPath();
183 ctx.moveTo(x, y);
184 ctx.lineTo(x + this.area.w, y);
185 ctx.closePath();
186 ctx.stroke();
187 }
188 }
189
190 if (this.attr_('drawXGrid')) {
191 ticks = this.layout.xticks;
192 ctx.save();
193 ctx.strokeStyle = this.attr_('gridLineColor');
194 ctx.lineWidth = this.attr_('gridLineWidth');
195 for (i=0; i<ticks.length; i++) {
196 x = halfUp(this.area.x + ticks[i][0] * this.area.w);
197 y = halfDown(this.area.y + this.area.h);
198 ctx.beginPath();
199 ctx.moveTo(x, y);
200 ctx.lineTo(x, this.area.y);
201 ctx.closePath();
202 ctx.stroke();
203 }
204 }
205
206 // Do the ordinary rendering, as before
207 this._renderLineChart();
208 this._renderAxis();
209 this._renderChartLabels();
210 this._renderAnnotations();
211 };
212
213 DygraphCanvasRenderer.prototype._createIEClipArea = function() {
214 var className = 'dygraph-clip-div';
215 var graphDiv = this.dygraph_.graphDiv;
216
217 // Remove old clip divs.
218 for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
219 if (graphDiv.childNodes[i].className == className) {
220 graphDiv.removeChild(graphDiv.childNodes[i]);
221 }
222 }
223
224 // Determine background color to give clip divs.
225 var backgroundColor = document.bgColor;
226 var element = this.dygraph_.graphDiv;
227 while (element != document) {
228 var bgcolor = element.currentStyle.backgroundColor;
229 if (bgcolor && bgcolor != 'transparent') {
230 backgroundColor = bgcolor;
231 break;
232 }
233 element = element.parentNode;
234 }
235
236 function createClipDiv(area) {
237 if (area.w === 0 || area.h === 0) {
238 return;
239 }
240 var elem = document.createElement('div');
241 elem.className = className;
242 elem.style.backgroundColor = backgroundColor;
243 elem.style.position = 'absolute';
244 elem.style.left = area.x + 'px';
245 elem.style.top = area.y + 'px';
246 elem.style.width = area.w + 'px';
247 elem.style.height = area.h + 'px';
248 graphDiv.appendChild(elem);
249 }
250
251 var plotArea = this.area;
252 // Left side
253 createClipDiv({
254 x:0, y:0,
255 w:plotArea.x,
256 h:this.height
257 });
258
259 // Top
260 createClipDiv({
261 x: plotArea.x, y: 0,
262 w: this.width - plotArea.x,
263 h: plotArea.y
264 });
265
266 // Right side
267 createClipDiv({
268 x: plotArea.x + plotArea.w, y: 0,
269 w: this.width-plotArea.x - plotArea.w,
270 h: this.height
271 });
272
273 // Bottom
274 createClipDiv({
275 x: plotArea.x,
276 y: plotArea.y + plotArea.h,
277 w: this.width - plotArea.x,
278 h: this.height - plotArea.h - plotArea.y
279 });
280 };
281
282 DygraphCanvasRenderer.prototype._renderAxis = function() {
283 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
284
285 // Round pixels to half-integer boundaries for crisper drawing.
286 function halfUp(x) { return Math.round(x) + 0.5; }
287 function halfDown(y){ return Math.round(y) - 0.5; }
288
289 var context = this.elementContext;
290
291 var label, x, y, tick, i;
292
293 var labelStyle = {
294 position: "absolute",
295 fontSize: this.attr_('axisLabelFontSize') + "px",
296 zIndex: 10,
297 color: this.attr_('axisLabelColor'),
298 width: this.attr_('axisLabelWidth') + "px",
299 // height: this.attr_('axisLabelFontSize') + 2 + "px",
300 lineHeight: "normal", // Something other than "normal" line-height screws up label positioning.
301 overflow: "hidden"
302 };
303 var makeDiv = function(txt, axis, prec_axis) {
304 var div = document.createElement("div");
305 for (var name in labelStyle) {
306 if (labelStyle.hasOwnProperty(name)) {
307 div.style[name] = labelStyle[name];
308 }
309 }
310 var inner_div = document.createElement("div");
311 inner_div.className = 'dygraph-axis-label' +
312 ' dygraph-axis-label-' + axis +
313 (prec_axis ? ' dygraph-axis-label-' + prec_axis : '');
314 inner_div.appendChild(document.createTextNode(txt));
315 div.appendChild(inner_div);
316 return div;
317 };
318
319 // axis lines
320 context.save();
321 context.strokeStyle = this.attr_('axisLineColor');
322 context.lineWidth = this.attr_('axisLineWidth');
323
324 if (this.attr_('drawYAxis')) {
325 if (this.layout.yticks && this.layout.yticks.length > 0) {
326 var num_axes = this.dygraph_.numAxes();
327 for (i = 0; i < this.layout.yticks.length; i++) {
328 tick = this.layout.yticks[i];
329 if (typeof(tick) == "function") return;
330 x = this.area.x;
331 var sgn = 1;
332 var prec_axis = 'y1';
333 if (tick[0] == 1) { // right-side y-axis
334 x = this.area.x + this.area.w;
335 sgn = -1;
336 prec_axis = 'y2';
337 }
338 y = this.area.y + tick[1] * this.area.h;
339
340 /* Tick marks are currently clipped, so don't bother drawing them.
341 context.beginPath();
342 context.moveTo(halfUp(x), halfDown(y));
343 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
344 context.closePath();
345 context.stroke();
346 */
347
348 label = makeDiv(tick[2], 'y', num_axes == 2 ? prec_axis : null);
349 var top = (y - this.attr_('axisLabelFontSize') / 2);
350 if (top < 0) top = 0;
351
352 if (top + this.attr_('axisLabelFontSize') + 3 > this.height) {
353 label.style.bottom = "0px";
354 } else {
355 label.style.top = top + "px";
356 }
357 if (tick[0] === 0) {
358 label.style.left = (this.area.x - this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
359 label.style.textAlign = "right";
360 } else if (tick[0] == 1) {
361 label.style.left = (this.area.x + this.area.w +
362 this.attr_('axisTickSize')) + "px";
363 label.style.textAlign = "left";
364 }
365 label.style.width = this.attr_('yAxisLabelWidth') + "px";
366 this.container.appendChild(label);
367 this.ylabels.push(label);
368 }
369
370 // The lowest tick on the y-axis often overlaps with the leftmost
371 // tick on the x-axis. Shift the bottom tick up a little bit to
372 // compensate if necessary.
373 var bottomTick = this.ylabels[0];
374 var fontSize = this.attr_('axisLabelFontSize');
375 var bottom = parseInt(bottomTick.style.top, 10) + fontSize;
376 if (bottom > this.height - fontSize) {
377 bottomTick.style.top = (parseInt(bottomTick.style.top, 10) -
378 fontSize / 2) + "px";
379 }
380 }
381
382 // draw a vertical line on the left to separate the chart from the labels.
383 context.beginPath();
384 context.moveTo(halfUp(this.area.x), halfDown(this.area.y));
385 context.lineTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
386 context.closePath();
387 context.stroke();
388
389 // if there's a secondary y-axis, draw a vertical line for that, too.
390 if (this.dygraph_.numAxes() == 2) {
391 context.beginPath();
392 context.moveTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y));
393 context.lineTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
394 context.closePath();
395 context.stroke();
396 }
397 }
398
399 if (this.attr_('drawXAxis')) {
400 if (this.layout.xticks) {
401 for (i = 0; i < this.layout.xticks.length; i++) {
402 tick = this.layout.xticks[i];
403 x = this.area.x + tick[0] * this.area.w;
404 y = this.area.y + this.area.h;
405
406 /* Tick marks are currently clipped, so don't bother drawing them.
407 context.beginPath();
408 context.moveTo(halfUp(x), halfDown(y));
409 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
410 context.closePath();
411 context.stroke();
412 */
413
414 label = makeDiv(tick[1], 'x');
415 label.style.textAlign = "center";
416 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
417
418 var left = (x - this.attr_('axisLabelWidth')/2);
419 if (left + this.attr_('axisLabelWidth') > this.width) {
420 left = this.width - this.attr_('xAxisLabelWidth');
421 label.style.textAlign = "right";
422 }
423 if (left < 0) {
424 left = 0;
425 label.style.textAlign = "left";
426 }
427
428 label.style.left = left + "px";
429 label.style.width = this.attr_('xAxisLabelWidth') + "px";
430 this.container.appendChild(label);
431 this.xlabels.push(label);
432 }
433 }
434
435 context.beginPath();
436 context.moveTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
437 context.lineTo(halfUp(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
438 context.closePath();
439 context.stroke();
440 }
441
442 context.restore();
443 };
444
445
446 DygraphCanvasRenderer.prototype._renderChartLabels = function() {
447 var div, class_div;
448
449 // Generate divs for the chart title, xlabel and ylabel.
450 // Space for these divs has already been taken away from the charting area in
451 // the DygraphCanvasRenderer constructor.
452 if (this.attr_('title')) {
453 div = document.createElement("div");
454 div.style.position = 'absolute';
455 div.style.top = '0px';
456 div.style.left = this.area.x + 'px';
457 div.style.width = this.area.w + 'px';
458 div.style.height = this.attr_('titleHeight') + 'px';
459 div.style.textAlign = 'center';
460 div.style.fontSize = (this.attr_('titleHeight') - 8) + 'px';
461 div.style.fontWeight = 'bold';
462 class_div = document.createElement("div");
463 class_div.className = 'dygraph-label dygraph-title';
464 class_div.innerHTML = this.attr_('title');
465 div.appendChild(class_div);
466 this.container.appendChild(div);
467 this.chartLabels.title = div;
468 }
469
470 if (this.attr_('xlabel')) {
471 div = document.createElement("div");
472 div.style.position = 'absolute';
473 div.style.bottom = 0; // TODO(danvk): this is lazy. Calculate style.top.
474 div.style.left = this.area.x + 'px';
475 div.style.width = this.area.w + 'px';
476 div.style.height = this.attr_('xLabelHeight') + 'px';
477 div.style.textAlign = 'center';
478 div.style.fontSize = (this.attr_('xLabelHeight') - 2) + 'px';
479
480 class_div = document.createElement("div");
481 class_div.className = 'dygraph-label dygraph-xlabel';
482 class_div.innerHTML = this.attr_('xlabel');
483 div.appendChild(class_div);
484 this.container.appendChild(div);
485 this.chartLabels.xlabel = div;
486 }
487
488 if (this.attr_('ylabel')) {
489 var box = {
490 left: 0,
491 top: this.area.y,
492 width: this.attr_('yLabelWidth'),
493 height: this.area.h
494 };
495 // TODO(danvk): is this outer div actually necessary?
496 div = document.createElement("div");
497 div.style.position = 'absolute';
498 div.style.left = box.left;
499 div.style.top = box.top + 'px';
500 div.style.width = box.width + 'px';
501 div.style.height = box.height + 'px';
502 div.style.fontSize = (this.attr_('yLabelWidth') - 2) + 'px';
503
504 var inner_div = document.createElement("div");
505 inner_div.style.position = 'absolute';
506 inner_div.style.width = box.height + 'px';
507 inner_div.style.height = box.width + 'px';
508 inner_div.style.top = (box.height / 2 - box.width / 2) + 'px';
509 inner_div.style.left = (box.width / 2 - box.height / 2) + 'px';
510 inner_div.style.textAlign = 'center';
511
512 // CSS rotation is an HTML5 feature which is not standardized. Hence every
513 // browser has its own name for the CSS style.
514 inner_div.style.transform = 'rotate(-90deg)'; // HTML5
515 inner_div.style.WebkitTransform = 'rotate(-90deg)'; // Safari/Chrome
516 inner_div.style.MozTransform = 'rotate(-90deg)'; // Firefox
517 inner_div.style.OTransform = 'rotate(-90deg)'; // Opera
518 inner_div.style.msTransform = 'rotate(-90deg)'; // IE9
519
520 if (typeof(document.documentMode) !== 'undefined' &&
521 document.documentMode < 9) {
522 // We're dealing w/ an old version of IE, so we have to rotate the text
523 // using a BasicImage transform. This uses a different origin of rotation
524 // than HTML5 rotation (top left of div vs. its center).
525 inner_div.style.filter =
526 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
527 inner_div.style.left = '0px';
528 inner_div.style.top = '0px';
529 }
530
531 class_div = document.createElement("div");
532 class_div.className = 'dygraph-label dygraph-ylabel';
533 class_div.innerHTML = this.attr_('ylabel');
534
535 inner_div.appendChild(class_div);
536 div.appendChild(inner_div);
537 this.container.appendChild(div);
538 this.chartLabels.ylabel = div;
539 }
540 };
541
542
543 DygraphCanvasRenderer.prototype._renderAnnotations = function() {
544 var annotationStyle = {
545 "position": "absolute",
546 "fontSize": this.attr_('axisLabelFontSize') + "px",
547 "zIndex": 10,
548 "overflow": "hidden"
549 };
550
551 var bindEvt = function(eventName, classEventName, p, self) {
552 return function(e) {
553 var a = p.annotation;
554 if (a.hasOwnProperty(eventName)) {
555 a[eventName](a, p, self.dygraph_, e);
556 } else if (self.dygraph_.attr_(classEventName)) {
557 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
558 }
559 };
560 };
561
562 // Get a list of point with annotations.
563 var points = this.layout.annotated_points;
564 for (var i = 0; i < points.length; i++) {
565 var p = points[i];
566 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
567 continue;
568 }
569
570 var a = p.annotation;
571 var tick_height = 6;
572 if (a.hasOwnProperty("tickHeight")) {
573 tick_height = a.tickHeight;
574 }
575
576 var div = document.createElement("div");
577 for (var name in annotationStyle) {
578 if (annotationStyle.hasOwnProperty(name)) {
579 div.style[name] = annotationStyle[name];
580 }
581 }
582 if (!a.hasOwnProperty('icon')) {
583 div.className = "dygraphDefaultAnnotation";
584 }
585 if (a.hasOwnProperty('cssClass')) {
586 div.className += " " + a.cssClass;
587 }
588
589 var width = a.hasOwnProperty('width') ? a.width : 16;
590 var height = a.hasOwnProperty('height') ? a.height : 16;
591 if (a.hasOwnProperty('icon')) {
592 var img = document.createElement("img");
593 img.src = a.icon;
594 img.width = width;
595 img.height = height;
596 div.appendChild(img);
597 } else if (p.annotation.hasOwnProperty('shortText')) {
598 div.appendChild(document.createTextNode(p.annotation.shortText));
599 }
600 div.style.left = (p.canvasx - width / 2) + "px";
601 if (a.attachAtBottom) {
602 div.style.top = (this.area.h - height - tick_height) + "px";
603 } else {
604 div.style.top = (p.canvasy - height - tick_height) + "px";
605 }
606 div.style.width = width + "px";
607 div.style.height = height + "px";
608 div.title = p.annotation.text;
609 div.style.color = this.colors[p.name];
610 div.style.borderColor = this.colors[p.name];
611 a.div = div;
612
613 Dygraph.addEvent(div, 'click',
614 bindEvt('clickHandler', 'annotationClickHandler', p, this));
615 Dygraph.addEvent(div, 'mouseover',
616 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
617 Dygraph.addEvent(div, 'mouseout',
618 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
619 Dygraph.addEvent(div, 'dblclick',
620 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
621
622 this.container.appendChild(div);
623 this.annotations.push(div);
624
625 var ctx = this.elementContext;
626 ctx.strokeStyle = this.colors[p.name];
627 ctx.beginPath();
628 if (!a.attachAtBottom) {
629 ctx.moveTo(p.canvasx, p.canvasy);
630 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
631 } else {
632 ctx.moveTo(p.canvasx, this.area.h);
633 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
634 }
635 ctx.closePath();
636 ctx.stroke();
637 }
638 };
639
640
641 /**
642 * Actually draw the lines chart, including error bars.
643 * TODO(danvk): split this into several smaller functions.
644 * @private
645 */
646 DygraphCanvasRenderer.prototype._renderLineChart = function() {
647 var isNullOrNaN = function(x) {
648 return (x === null || isNaN(x));
649 };
650
651 // TODO(danvk): use this.attr_ for many of these.
652 var context = this.elementContext;
653 var fillAlpha = this.attr_('fillAlpha');
654 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
655 var fillGraph = this.attr_("fillGraph");
656 var stackedGraph = this.attr_("stackedGraph");
657 var stepPlot = this.attr_("stepPlot");
658 var points = this.layout.points;
659 var pointsLength = points.length;
660 var point, i, j, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis;
661
662 var setNames = [];
663 for (var name in this.layout.datasets) {
664 if (this.layout.datasets.hasOwnProperty(name)) {
665 setNames.push(name);
666 }
667 }
668 var setCount = setNames.length;
669
670 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
671 this.colors = {};
672 for (i = 0; i < setCount; i++) {
673 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
674 }
675
676 // Update Points
677 // TODO(danvk): here
678 for (i = pointsLength; i--;) {
679 point = points[i];
680 point.canvasx = this.area.w * point.x + this.area.x;
681 point.canvasy = this.area.h * point.y + this.area.y;
682 }
683
684 // create paths
685 var ctx = context;
686 if (errorBars) {
687 if (fillGraph) {
688 this.dygraph_.warn("Can't use fillGraph option with error bars");
689 }
690
691 for (i = 0; i < setCount; i++) {
692 setName = setNames[i];
693 axis = this.dygraph_.axisPropertiesForSeries(setName);
694 color = this.colors[setName];
695
696 // setup graphics context
697 ctx.save();
698 prevX = NaN;
699 prevY = NaN;
700 prevYs = [-1, -1];
701 yscale = axis.yscale;
702 // should be same color as the lines but only 15% opaque.
703 rgb = new RGBColor(color);
704 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
705 fillAlpha + ')';
706 ctx.fillStyle = err_color;
707 ctx.beginPath();
708 for (j = 0; j < pointsLength; j++) {
709 point = points[j];
710 if (point.name == setName) {
711 if (!Dygraph.isOK(point.y)) {
712 prevX = NaN;
713 continue;
714 }
715
716 // TODO(danvk): here
717 if (stepPlot) {
718 newYs = [ point.y_bottom, point.y_top ];
719 prevY = point.y;
720 } else {
721 newYs = [ point.y_bottom, point.y_top ];
722 }
723 newYs[0] = this.area.h * newYs[0] + this.area.y;
724 newYs[1] = this.area.h * newYs[1] + this.area.y;
725 if (!isNaN(prevX)) {
726 if (stepPlot) {
727 ctx.moveTo(prevX, newYs[0]);
728 } else {
729 ctx.moveTo(prevX, prevYs[0]);
730 }
731 ctx.lineTo(point.canvasx, newYs[0]);
732 ctx.lineTo(point.canvasx, newYs[1]);
733 if (stepPlot) {
734 ctx.lineTo(prevX, newYs[1]);
735 } else {
736 ctx.lineTo(prevX, prevYs[1]);
737 }
738 ctx.closePath();
739 }
740 prevYs = newYs;
741 prevX = point.canvasx;
742 }
743 }
744 ctx.fill();
745 }
746 } else if (fillGraph) {
747 var baseline = []; // for stacked graphs: baseline for filling
748
749 // process sets in reverse order (needed for stacked graphs)
750 for (i = setCount - 1; i >= 0; i--) {
751 setName = setNames[i];
752 color = this.colors[setName];
753 axis = this.dygraph_.axisPropertiesForSeries(setName);
754 var axisY = 1.0 + axis.minyval * axis.yscale;
755 if (axisY < 0.0) axisY = 0.0;
756 else if (axisY > 1.0) axisY = 1.0;
757 axisY = this.area.h * axisY + this.area.y;
758
759 // setup graphics context
760 ctx.save();
761 prevX = NaN;
762 prevYs = [-1, -1];
763 yscale = axis.yscale;
764 // should be same color as the lines but only 15% opaque.
765 rgb = new RGBColor(color);
766 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
767 fillAlpha + ')';
768 ctx.fillStyle = err_color;
769 ctx.beginPath();
770 for (j = 0; j < pointsLength; j++) {
771 point = points[j];
772 if (point.name == setName) {
773 if (!Dygraph.isOK(point.y)) {
774 prevX = NaN;
775 continue;
776 }
777 if (stackedGraph) {
778 var lastY = baseline[point.canvasx];
779 if (lastY === undefined) lastY = axisY;
780 baseline[point.canvasx] = point.canvasy;
781 newYs = [ point.canvasy, lastY ];
782 } else {
783 newYs = [ point.canvasy, axisY ];
784 }
785 if (!isNaN(prevX)) {
786 ctx.moveTo(prevX, prevYs[0]);
787 if (stepPlot) {
788 ctx.lineTo(point.canvasx, prevYs[0]);
789 } else {
790 ctx.lineTo(point.canvasx, newYs[0]);
791 }
792 ctx.lineTo(point.canvasx, newYs[1]);
793 ctx.lineTo(prevX, prevYs[1]);
794 ctx.closePath();
795 }
796 prevYs = newYs;
797 prevX = point.canvasx;
798 }
799 }
800 ctx.fill();
801 }
802 }
803
804 // Drawing the lines.
805 var firstIndexInSet = 0;
806 var afterLastIndexInSet = 0;
807 var setLength = 0;
808 for (i = 0; i < setCount; i += 1) {
809 setLength = this.layout.setPointsLengths[i];
810 afterLastIndexInSet += setLength;
811 setName = setNames[i];
812 color = this.colors[setName];
813 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
814
815 // setup graphics context
816 context.save();
817 var pointSize = this.dygraph_.attr_("pointSize", setName);
818 prevX = null;
819 prevY = null;
820 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
821 for (j = firstIndexInSet; j < afterLastIndexInSet; j++) {
822 point = points[j];
823 if (isNullOrNaN(point.canvasy)) {
824 if (stepPlot && prevX !== null) {
825 // Draw a horizontal line to the start of the missing data
826 ctx.beginPath();
827 ctx.strokeStyle = color;
828 ctx.lineWidth = this.attr_('strokeWidth');
829 ctx.moveTo(prevX, prevY);
830 ctx.lineTo(point.canvasx, prevY);
831 ctx.stroke();
832 }
833 // this will make us move to the next point, not draw a line to it.
834 prevX = prevY = null;
835 } else {
836 // A point is "isolated" if it is non-null but both the previous
837 // and next points are null.
838 var isIsolated = (!prevX && (j == points.length - 1 ||
839 isNullOrNaN(points[j+1].canvasy)));
840 if (prevX === null) {
841 prevX = point.canvasx;
842 prevY = point.canvasy;
843 } else {
844 // Skip over points that will be drawn in the same pixel.
845 if (Math.round(prevX) == Math.round(point.canvasx) &&
846 Math.round(prevY) == Math.round(point.canvasy)) {
847 continue;
848 }
849 // TODO(antrob): skip over points that lie on a line that is already
850 // going to be drawn. There is no need to have more than 2
851 // consecutive points that are collinear.
852 if (strokeWidth) {
853 ctx.beginPath();
854 ctx.strokeStyle = color;
855 ctx.lineWidth = strokeWidth;
856 ctx.moveTo(prevX, prevY);
857 if (stepPlot) {
858 ctx.lineTo(point.canvasx, prevY);
859 }
860 prevX = point.canvasx;
861 prevY = point.canvasy;
862 ctx.lineTo(prevX, prevY);
863 ctx.stroke();
864 }
865 }
866
867 if (drawPoints || isIsolated) {
868 ctx.beginPath();
869 ctx.fillStyle = color;
870 ctx.arc(point.canvasx, point.canvasy, pointSize,
871 0, 2 * Math.PI, false);
872 ctx.fill();
873 }
874 }
875 }
876 firstIndexInSet = afterLastIndexInSet;
877 }
878
879 context.restore();
880 };