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