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