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