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