Checkpoint: annotations fully ported to plugin system. All tests pass.
[dygraphs.git] / dygraph-canvas.js
1 /**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
11 * In particular, support for:
12 * - grid overlays
13 * - error bars
14 * - dygraphs attribute system
15 */
16
17 /**
18 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
19 * a canvas. It's based on PlotKit.CanvasRenderer.
20 * @param {Object} element The canvas to attach to
21 * @param {Object} elementContext The 2d context of the canvas (injected so it
22 * can be mocked for testing.)
23 * @param {Layout} layout The DygraphLayout object for this graph.
24 * @constructor
25 */
26
27 /*jshint globalstrict: true */
28 /*global Dygraph:false,RGBColor:false */
29 "use strict";
30
31
32 /**
33 * @constructor
34 *
35 * This gets called when there are "new points" to chart. This is generally the
36 * case when the underlying data being charted has changed. It is _not_ called
37 * in the common case that the user has zoomed or is panning the view.
38 *
39 * The chart canvas has already been created by the Dygraph object. The
40 * renderer simply gets a drawing context.
41 *
42 * @param {Dyraph} dygraph The chart to which this renderer belongs.
43 * @param {Canvas} element The <canvas> DOM element on which to draw.
44 * @param {CanvasRenderingContext2D} elementContext The drawing context.
45 * @param {DygraphLayout} layout The chart's DygraphLayout object.
46 *
47 * TODO(danvk): remove the elementContext property.
48 */
49 var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
50 this.dygraph_ = dygraph;
51
52 this.layout = layout;
53 this.element = element;
54 this.elementContext = elementContext;
55 this.container = this.element.parentNode;
56
57 this.height = this.element.height;
58 this.width = this.element.width;
59
60 // --- check whether everything is ok before we return
61 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
62 throw "Canvas is not supported.";
63
64 // internal state
65 this.xlabels = [];
66 this.ylabels = [];
67 this.annotations = [];
68
69 this.area = layout.getPlotArea();
70 this.container.style.position = "relative";
71 this.container.style.width = this.width + "px";
72
73 // Set up a clipping area for the canvas (and the interaction canvas).
74 // This ensures that we don't overdraw.
75 if (this.dygraph_.isUsingExcanvas_) {
76 this._createIEClipArea();
77 } else {
78 // on Android 3 and 4, setting a clipping area on a canvas prevents it from
79 // displaying anything.
80 if (!Dygraph.isAndroid()) {
81 var ctx = this.dygraph_.canvas_ctx_;
82 ctx.beginPath();
83 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
84 ctx.clip();
85
86 ctx = this.dygraph_.hidden_ctx_;
87 ctx.beginPath();
88 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
89 ctx.clip();
90 }
91 }
92 };
93
94 DygraphCanvasRenderer.prototype.attr_ = function(x) {
95 return this.dygraph_.attr_(x);
96 };
97
98 /**
99 * Clears out all chart content and DOM elements.
100 * This is called immediately before render() on every frame, including
101 * during zooms and pans.
102 * @private
103 */
104 DygraphCanvasRenderer.prototype.clear = function() {
105 var context;
106 if (this.isIE) {
107 // VML takes a while to start up, so we just poll every this.IEDelay
108 try {
109 if (this.clearDelay) {
110 this.clearDelay.cancel();
111 this.clearDelay = null;
112 }
113 context = this.elementContext;
114 }
115 catch (e) {
116 // TODO(danvk): this is broken, since MochiKit.Async is gone.
117 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
118 // this.clearDelay.addCallback(bind(this.clear, this));
119 return;
120 }
121 }
122
123 context = this.elementContext;
124 context.clearRect(0, 0, this.width, this.height);
125
126 function removeArray(ary) {
127 for (var i = 0; i < ary.length; i++) {
128 var el = ary[i];
129 if (el.parentNode) el.parentNode.removeChild(el);
130 }
131 }
132
133 removeArray(this.xlabels);
134 removeArray(this.ylabels);
135 removeArray(this.annotations);
136
137 this.xlabels = [];
138 this.ylabels = [];
139 this.annotations = [];
140 };
141
142 /**
143 * Checks whether the browser supports the &lt;canvas&gt; tag.
144 * @private
145 */
146 DygraphCanvasRenderer.isSupported = function(canvasName) {
147 var canvas = null;
148 try {
149 if (typeof(canvasName) == 'undefined' || canvasName === null) {
150 canvas = document.createElement("canvas");
151 } else {
152 canvas = canvasName;
153 }
154 canvas.getContext("2d");
155 }
156 catch (e) {
157 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
158 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
159 if ((!ie) || (ie[1] < 6) || (opera))
160 return false;
161 return true;
162 }
163 return true;
164 };
165
166 /**
167 * @param { [String] } colors Array of color strings. Should have one entry for
168 * each series to be rendered.
169 */
170 DygraphCanvasRenderer.prototype.setColors = function(colors) {
171 this.colorScheme_ = colors;
172 };
173
174 /**
175 * This method is responsible for drawing everything on the chart, including
176 * lines, error bars, fills and axes.
177 * It is called immediately after clear() on every frame, including during pans
178 * and zooms.
179 * @private
180 */
181 DygraphCanvasRenderer.prototype.render = function() {
182 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
183 // half-integers. This prevents them from drawing in two rows/cols.
184 var ctx = this.elementContext;
185 function halfUp(x) { return Math.round(x) + 0.5; }
186 function halfDown(y){ return Math.round(y) - 0.5; }
187
188 if (this.attr_('underlayCallback')) {
189 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
190 // users who expect a deprecated form of this callback.
191 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
192 }
193
194 var x, y, i, ticks;
195 if (this.attr_('drawYGrid')) {
196 ticks = this.layout.yticks;
197 // TODO(konigsberg): I don't think these calls to save() have a corresponding restore().
198 ctx.save();
199 ctx.strokeStyle = this.attr_('gridLineColor');
200 ctx.lineWidth = this.attr_('gridLineWidth');
201 for (i = 0; i < ticks.length; i++) {
202 // TODO(danvk): allow secondary axes to draw a grid, too.
203 if (ticks[i][0] !== 0) continue;
204 x = halfUp(this.area.x);
205 y = halfDown(this.area.y + ticks[i][1] * this.area.h);
206 ctx.beginPath();
207 ctx.moveTo(x, y);
208 ctx.lineTo(x + this.area.w, y);
209 ctx.closePath();
210 ctx.stroke();
211 }
212 ctx.restore();
213 }
214
215 if (this.attr_('drawXGrid')) {
216 ticks = this.layout.xticks;
217 ctx.save();
218 ctx.strokeStyle = this.attr_('gridLineColor');
219 ctx.lineWidth = this.attr_('gridLineWidth');
220 for (i=0; i<ticks.length; i++) {
221 x = halfUp(this.area.x + ticks[i][0] * this.area.w);
222 y = halfDown(this.area.y + this.area.h);
223 ctx.beginPath();
224 ctx.moveTo(x, y);
225 ctx.lineTo(x, this.area.y);
226 ctx.closePath();
227 ctx.stroke();
228 }
229 ctx.restore();
230 }
231
232 // Do the ordinary rendering, as before
233 this._renderLineChart();
234 this._renderAxis();
235 };
236
237 DygraphCanvasRenderer.prototype._createIEClipArea = function() {
238 var className = 'dygraph-clip-div';
239 var graphDiv = this.dygraph_.graphDiv;
240
241 // Remove old clip divs.
242 for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
243 if (graphDiv.childNodes[i].className == className) {
244 graphDiv.removeChild(graphDiv.childNodes[i]);
245 }
246 }
247
248 // Determine background color to give clip divs.
249 var backgroundColor = document.bgColor;
250 var element = this.dygraph_.graphDiv;
251 while (element != document) {
252 var bgcolor = element.currentStyle.backgroundColor;
253 if (bgcolor && bgcolor != 'transparent') {
254 backgroundColor = bgcolor;
255 break;
256 }
257 element = element.parentNode;
258 }
259
260 function createClipDiv(area) {
261 if (area.w === 0 || area.h === 0) {
262 return;
263 }
264 var elem = document.createElement('div');
265 elem.className = className;
266 elem.style.backgroundColor = backgroundColor;
267 elem.style.position = 'absolute';
268 elem.style.left = area.x + 'px';
269 elem.style.top = area.y + 'px';
270 elem.style.width = area.w + 'px';
271 elem.style.height = area.h + 'px';
272 graphDiv.appendChild(elem);
273 }
274
275 var plotArea = this.area;
276 // Left side
277 createClipDiv({
278 x:0, y:0,
279 w:plotArea.x,
280 h:this.height
281 });
282
283 // Top
284 createClipDiv({
285 x: plotArea.x, y: 0,
286 w: this.width - plotArea.x,
287 h: plotArea.y
288 });
289
290 // Right side
291 createClipDiv({
292 x: plotArea.x + plotArea.w, y: 0,
293 w: this.width-plotArea.x - plotArea.w,
294 h: this.height
295 });
296
297 // Bottom
298 createClipDiv({
299 x: plotArea.x,
300 y: plotArea.y + plotArea.h,
301 w: this.width - plotArea.x,
302 h: this.height - plotArea.h - plotArea.y
303 });
304 };
305
306 DygraphCanvasRenderer.prototype._renderAxis = function() {
307 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
308
309 // Round pixels to half-integer boundaries for crisper drawing.
310 function halfUp(x) { return Math.round(x) + 0.5; }
311 function halfDown(y){ return Math.round(y) - 0.5; }
312
313 var context = this.elementContext;
314
315 var label, x, y, tick, i;
316
317 var labelStyle = {
318 position: "absolute",
319 fontSize: this.attr_('axisLabelFontSize') + "px",
320 zIndex: 10,
321 color: this.attr_('axisLabelColor'),
322 width: this.attr_('axisLabelWidth') + "px",
323 // height: this.attr_('axisLabelFontSize') + 2 + "px",
324 lineHeight: "normal", // Something other than "normal" line-height screws up label positioning.
325 overflow: "hidden"
326 };
327 var makeDiv = function(txt, axis, prec_axis) {
328 var div = document.createElement("div");
329 for (var name in labelStyle) {
330 if (labelStyle.hasOwnProperty(name)) {
331 div.style[name] = labelStyle[name];
332 }
333 }
334 var inner_div = document.createElement("div");
335 inner_div.className = 'dygraph-axis-label' +
336 ' dygraph-axis-label-' + axis +
337 (prec_axis ? ' dygraph-axis-label-' + prec_axis : '');
338 inner_div.innerHTML=txt;
339 div.appendChild(inner_div);
340 return div;
341 };
342
343 // axis lines
344 context.save();
345 context.strokeStyle = this.attr_('axisLineColor');
346 context.lineWidth = this.attr_('axisLineWidth');
347
348 if (this.attr_('drawYAxis')) {
349 if (this.layout.yticks && this.layout.yticks.length > 0) {
350 var num_axes = this.dygraph_.numAxes();
351 for (i = 0; i < this.layout.yticks.length; i++) {
352 tick = this.layout.yticks[i];
353 if (typeof(tick) == "function") return;
354 x = this.area.x;
355 var sgn = 1;
356 var prec_axis = 'y1';
357 if (tick[0] == 1) { // right-side y-axis
358 x = this.area.x + this.area.w;
359 sgn = -1;
360 prec_axis = 'y2';
361 }
362 y = this.area.y + tick[1] * this.area.h;
363
364 /* Tick marks are currently clipped, so don't bother drawing them.
365 context.beginPath();
366 context.moveTo(halfUp(x), halfDown(y));
367 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
368 context.closePath();
369 context.stroke();
370 */
371
372 label = makeDiv(tick[2], 'y', num_axes == 2 ? prec_axis : null);
373 var top = (y - this.attr_('axisLabelFontSize') / 2);
374 if (top < 0) top = 0;
375
376 if (top + this.attr_('axisLabelFontSize') + 3 > this.height) {
377 label.style.bottom = "0px";
378 } else {
379 label.style.top = top + "px";
380 }
381 if (tick[0] === 0) {
382 label.style.left = (this.area.x - this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
383 label.style.textAlign = "right";
384 } else if (tick[0] == 1) {
385 label.style.left = (this.area.x + this.area.w +
386 this.attr_('axisTickSize')) + "px";
387 label.style.textAlign = "left";
388 }
389 label.style.width = this.attr_('yAxisLabelWidth') + "px";
390 this.container.appendChild(label);
391 this.ylabels.push(label);
392 }
393
394 // The lowest tick on the y-axis often overlaps with the leftmost
395 // tick on the x-axis. Shift the bottom tick up a little bit to
396 // compensate if necessary.
397 var bottomTick = this.ylabels[0];
398 var fontSize = this.attr_('axisLabelFontSize');
399 var bottom = parseInt(bottomTick.style.top, 10) + fontSize;
400 if (bottom > this.height - fontSize) {
401 bottomTick.style.top = (parseInt(bottomTick.style.top, 10) -
402 fontSize / 2) + "px";
403 }
404 }
405
406 // draw a vertical line on the left to separate the chart from the labels.
407 var axisX;
408 if (this.attr_('drawAxesAtZero')) {
409 var r = this.dygraph_.toPercentXCoord(0);
410 if (r > 1 || r < 0) r = 0;
411 axisX = halfUp(this.area.x + r * this.area.w);
412 } else {
413 axisX = halfUp(this.area.x);
414 }
415 context.beginPath();
416 context.moveTo(axisX, halfDown(this.area.y));
417 context.lineTo(axisX, halfDown(this.area.y + this.area.h));
418 context.closePath();
419 context.stroke();
420
421 // if there's a secondary y-axis, draw a vertical line for that, too.
422 if (this.dygraph_.numAxes() == 2) {
423 context.beginPath();
424 context.moveTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y));
425 context.lineTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
426 context.closePath();
427 context.stroke();
428 }
429 }
430
431 if (this.attr_('drawXAxis')) {
432 if (this.layout.xticks) {
433 for (i = 0; i < this.layout.xticks.length; i++) {
434 tick = this.layout.xticks[i];
435 x = this.area.x + tick[0] * this.area.w;
436 y = this.area.y + this.area.h;
437
438 /* Tick marks are currently clipped, so don't bother drawing them.
439 context.beginPath();
440 context.moveTo(halfUp(x), halfDown(y));
441 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
442 context.closePath();
443 context.stroke();
444 */
445
446 label = makeDiv(tick[1], 'x');
447 label.style.textAlign = "center";
448 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
449
450 var left = (x - this.attr_('axisLabelWidth')/2);
451 if (left + this.attr_('axisLabelWidth') > this.width) {
452 left = this.width - this.attr_('xAxisLabelWidth');
453 label.style.textAlign = "right";
454 }
455 if (left < 0) {
456 left = 0;
457 label.style.textAlign = "left";
458 }
459
460 label.style.left = left + "px";
461 label.style.width = this.attr_('xAxisLabelWidth') + "px";
462 this.container.appendChild(label);
463 this.xlabels.push(label);
464 }
465 }
466
467 context.beginPath();
468 var axisY;
469 if (this.attr_('drawAxesAtZero')) {
470 var r = this.dygraph_.toPercentYCoord(0, 0);
471 if (r > 1 || r < 0) r = 1;
472 axisY = halfDown(this.area.y + r * this.area.h);
473 } else {
474 axisY = halfDown(this.area.y + this.area.h);
475 }
476 context.moveTo(halfUp(this.area.x), axisY);
477 context.lineTo(halfUp(this.area.x + this.area.w), axisY);
478 context.closePath();
479 context.stroke();
480 }
481
482 context.restore();
483 };
484
485
486 /**
487 * Returns a predicate to be used with an iterator, which will
488 * iterate over points appropriately, depending on whether
489 * connectSeparatedPoints is true. When it's false, the predicate will
490 * skip over points with missing yVals.
491 */
492 DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
493 return connectSeparatedPoints ? DygraphCanvasRenderer._predicateThatSkipsEmptyPoints : null;
494 }
495
496 DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
497 function(array, idx) { return array[idx].yval !== null; }
498
499 DygraphCanvasRenderer.prototype._drawStyledLine = function(
500 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
501 drawPointCallback, pointSize) {
502 // TODO(konigsberg): Compute attributes outside this method call.
503 var stepPlot = this.attr_("stepPlot");
504 var firstIndexInSet = this.layout.setPointsOffsets[i];
505 var setLength = this.layout.setPointsLengths[i];
506 var points = this.layout.points;
507 if (!Dygraph.isArrayLike(strokePattern)) {
508 strokePattern = null;
509 }
510 var drawGapPoints = this.dygraph_.attr_('drawGapEdgePoints', setName);
511
512 ctx.save();
513
514 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
515 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
516
517 var pointsOnLine;
518 var strategy;
519 if (!strokePattern || strokePattern.length <= 1) {
520 strategy = trivialStrategy(ctx, color, strokeWidth);
521 } else {
522 strategy = nonTrivialStrategy(this, ctx, color, strokeWidth, strokePattern);
523 }
524 pointsOnLine = this._drawSeries(ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, strategy);
525 this._drawPointsOnLine(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize);
526
527 ctx.restore();
528 };
529
530 var nonTrivialStrategy = function(renderer, ctx, color, strokeWidth, strokePattern) {
531 return new function() {
532 this.init = function() { };
533 this.finish = function() { };
534 this.startSegment = function() {
535 ctx.beginPath();
536 ctx.strokeStyle = color;
537 ctx.lineWidth = strokeWidth;
538 };
539 this.endSegment = function() {
540 ctx.stroke(); // should this include closePath?
541 };
542 this.drawLine = function(x1, y1, x2, y2) {
543 renderer._dashedLine(ctx, x1, y1, x2, y2, strokePattern);
544 };
545 this.skipPixel = function(prevX, prevY, curX, curY) {
546 // TODO(konigsberg): optimize with http://jsperf.com/math-round-vs-hack/6 ?
547 return (Math.round(prevX) == Math.round(curX) &&
548 Math.round(prevY) == Math.round(curY));
549 };
550 };
551 };
552
553 var trivialStrategy = function(ctx, color, strokeWidth) {
554 return new function() {
555 this.init = function() {
556 ctx.beginPath();
557 ctx.strokeStyle = color;
558 ctx.lineWidth = strokeWidth;
559 };
560 this.finish = function() {
561 ctx.stroke(); // should this include closePath?
562 };
563 this.startSegment = function() { };
564 this.endSegment = function() { };
565 this.drawLine = function(x1, y1, x2, y2) {
566 ctx.moveTo(x1, y1);
567 ctx.lineTo(x2, y2);
568 };
569 // don't skip pixels.
570 this.skipPixel = function() {
571 return false;
572 };
573 };
574 };
575
576 DygraphCanvasRenderer.prototype._drawPointsOnLine = function(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize) {
577 for (var idx = 0; idx < pointsOnLine.length; idx++) {
578 var cb = pointsOnLine[idx];
579 ctx.save();
580 drawPointCallback(
581 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
582 ctx.restore();
583 }
584 }
585
586 DygraphCanvasRenderer.prototype._drawSeries = function(
587 ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints,
588 stepPlot, strategy) {
589
590 var prevCanvasX = null;
591 var prevCanvasY = null;
592 var nextCanvasY = null;
593 var isIsolated; // true if this point is isolated (no line segments)
594 var point; // the point being processed in the while loop
595 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
596 var first = true; // the first cycle through the while loop
597
598 strategy.init();
599
600 while(iter.hasNext()) {
601 point = iter.next();
602 if (point.canvasy === null || point.canvasy != point.canvasy) {
603 if (stepPlot && prevCanvasX !== null) {
604 // Draw a horizontal line to the start of the missing data
605 strategy.startSegment();
606 strategy.drawLine(prevX, prevY, point.canvasx, prevY);
607 strategy.endSegment();
608 }
609 prevCanvasX = prevCanvasY = null;
610 } else {
611 nextCanvasY = iter.hasNext() ? iter.peek().canvasy : null;
612 // TODO: we calculate isNullOrNaN for this point, and the next, and then, when
613 // we iterate, test for isNullOrNaN again. Why bother?
614 var isNextCanvasYNullOrNaN = nextCanvasY === null || nextCanvasY != nextCanvasY;
615 isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
616 if (drawGapPoints) {
617 // Also consider a point to be "isolated" if it's adjacent to a
618 // null point, excluding the graph edges.
619 if ((!first && !prevCanvasX) ||
620 (iter.hasNext() && isNextCanvasYNullOrNaN)) {
621 isIsolated = true;
622 }
623 }
624 if (prevCanvasX !== null) {
625 if (strategy.skipPixel(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy)) {
626 continue;
627 }
628 if (strokeWidth) {
629 strategy.startSegment();
630 if (stepPlot) {
631 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, prevCanvasY);
632 prevCanvasX = point.canvasx;
633 }
634 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy);
635 strategy.endSegment();
636 }
637 }
638 if (drawPoints || isIsolated) {
639 pointsOnLine.push([point.canvasx, point.canvasy]);
640 }
641 prevCanvasX = point.canvasx;
642 prevCanvasY = point.canvasy;
643 }
644 first = false;
645 }
646 strategy.finish();
647 return pointsOnLine;
648 };
649
650 DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
651 var setNames = this.layout.setNames;
652 var setName = setNames[i];
653
654 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
655 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
656 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
657 Dygraph.Circles.DEFAULT;
658
659 if (borderWidth && strokeWidth) {
660 this._drawStyledLine(ctx, i, setName,
661 this.dygraph_.attr_("strokeBorderColor", setName),
662 strokeWidth + 2 * borderWidth,
663 this.dygraph_.attr_("strokePattern", setName),
664 this.dygraph_.attr_("drawPoints", setName),
665 drawPointCallback,
666 this.dygraph_.attr_("pointSize", setName));
667 }
668
669 this._drawStyledLine(ctx, i, setName,
670 this.colors[setName],
671 strokeWidth,
672 this.dygraph_.attr_("strokePattern", setName),
673 this.dygraph_.attr_("drawPoints", setName),
674 drawPointCallback,
675 this.dygraph_.attr_("pointSize", setName));
676 };
677
678 /**
679 * Actually draw the lines chart, including error bars.
680 * TODO(danvk): split this into several smaller functions.
681 * @private
682 */
683 DygraphCanvasRenderer.prototype._renderLineChart = function() {
684 // TODO(danvk): use this.attr_ for many of these.
685 var ctx = this.elementContext;
686 var fillAlpha = this.attr_('fillAlpha');
687 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
688 var fillGraph = this.attr_("fillGraph");
689 var stackedGraph = this.attr_("stackedGraph");
690 var stepPlot = this.attr_("stepPlot");
691 var points = this.layout.points;
692 var pointsLength = points.length;
693 var point, i, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis;
694
695 var setNames = this.layout.setNames;
696 var setCount = setNames.length;
697
698 this.colors = this.dygraph_.colorsMap_;
699
700 // Update Points
701 // TODO(danvk): here
702 //
703 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
704 // transformations can be pushed into the canvas via linear transformation
705 // matrices.
706 for (i = pointsLength; i--;) {
707 point = points[i];
708 point.canvasx = this.area.w * point.x + this.area.x;
709 point.canvasy = this.area.h * point.y + this.area.y;
710 }
711
712 // create paths
713 if (errorBars) {
714 ctx.save();
715 if (fillGraph) {
716 this.dygraph_.warn("Can't use fillGraph option with error bars");
717 }
718
719 for (i = 0; i < setCount; i++) {
720 setName = setNames[i];
721 axis = this.dygraph_.axisPropertiesForSeries(setName);
722 color = this.colors[setName];
723
724 var firstIndexInSet = this.layout.setPointsOffsets[i];
725 var setLength = this.layout.setPointsLengths[i];
726
727 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
728 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
729
730 // setup graphics context
731 prevX = NaN;
732 prevY = NaN;
733 prevYs = [-1, -1];
734 yscale = axis.yscale;
735 // should be same color as the lines but only 15% opaque.
736 rgb = new RGBColor(color);
737 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
738 fillAlpha + ')';
739 ctx.fillStyle = err_color;
740 ctx.beginPath();
741 while (iter.hasNext()) {
742 point = iter.next();
743 if (point.name == setName) { // TODO(klausw): this is always true
744 if (!Dygraph.isOK(point.y)) {
745 prevX = NaN;
746 continue;
747 }
748
749 // TODO(danvk): here
750 if (stepPlot) {
751 newYs = [ point.y_bottom, point.y_top ];
752 prevY = point.y;
753 } else {
754 newYs = [ point.y_bottom, point.y_top ];
755 }
756 newYs[0] = this.area.h * newYs[0] + this.area.y;
757 newYs[1] = this.area.h * newYs[1] + this.area.y;
758 if (!isNaN(prevX)) {
759 if (stepPlot) {
760 ctx.moveTo(prevX, newYs[0]);
761 } else {
762 ctx.moveTo(prevX, prevYs[0]);
763 }
764 ctx.lineTo(point.canvasx, newYs[0]);
765 ctx.lineTo(point.canvasx, newYs[1]);
766 if (stepPlot) {
767 ctx.lineTo(prevX, newYs[1]);
768 } else {
769 ctx.lineTo(prevX, prevYs[1]);
770 }
771 ctx.closePath();
772 }
773 prevYs = newYs;
774 prevX = point.canvasx;
775 }
776 }
777 ctx.fill();
778 }
779 ctx.restore();
780 } else if (fillGraph) {
781 ctx.save();
782 var baseline = {}; // for stacked graphs: baseline for filling
783 var currBaseline;
784
785 // process sets in reverse order (needed for stacked graphs)
786 for (i = setCount - 1; i >= 0; i--) {
787 setName = setNames[i];
788 color = this.colors[setName];
789 axis = this.dygraph_.axisPropertiesForSeries(setName);
790 var axisY = 1.0 + axis.minyval * axis.yscale;
791 if (axisY < 0.0) axisY = 0.0;
792 else if (axisY > 1.0) axisY = 1.0;
793 axisY = this.area.h * axisY + this.area.y;
794 var firstIndexInSet = this.layout.setPointsOffsets[i];
795 var setLength = this.layout.setPointsLengths[i];
796
797 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
798 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
799
800 // setup graphics context
801 prevX = NaN;
802 prevYs = [-1, -1];
803 yscale = axis.yscale;
804 // should be same color as the lines but only 15% opaque.
805 rgb = new RGBColor(color);
806 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
807 fillAlpha + ')';
808 ctx.fillStyle = err_color;
809 ctx.beginPath();
810 while(iter.hasNext()) {
811 point = iter.next();
812 if (point.name == setName) { // TODO(klausw): this is always true
813 if (!Dygraph.isOK(point.y)) {
814 prevX = NaN;
815 continue;
816 }
817 if (stackedGraph) {
818 currBaseline = baseline[point.canvasx];
819 var lastY;
820 if (currBaseline === undefined) {
821 lastY = axisY;
822 } else {
823 if(stepPlot) {
824 lastY = currBaseline[0];
825 } else {
826 lastY = currBaseline;
827 }
828 }
829 newYs = [ point.canvasy, lastY ];
830
831 if(stepPlot) {
832 // Step plots must keep track of the top and bottom of
833 // the baseline at each point.
834 if(prevYs[0] === -1) {
835 baseline[point.canvasx] = [ point.canvasy, axisY ];
836 } else {
837 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
838 }
839 } else {
840 baseline[point.canvasx] = point.canvasy;
841 }
842
843 } else {
844 newYs = [ point.canvasy, axisY ];
845 }
846 if (!isNaN(prevX)) {
847 ctx.moveTo(prevX, prevYs[0]);
848
849 if (stepPlot) {
850 ctx.lineTo(point.canvasx, prevYs[0]);
851 if(currBaseline) {
852 // Draw to the bottom of the baseline
853 ctx.lineTo(point.canvasx, currBaseline[1]);
854 } else {
855 ctx.lineTo(point.canvasx, newYs[1]);
856 }
857 } else {
858 ctx.lineTo(point.canvasx, newYs[0]);
859 ctx.lineTo(point.canvasx, newYs[1]);
860 }
861
862 ctx.lineTo(prevX, prevYs[1]);
863 ctx.closePath();
864 }
865 prevYs = newYs;
866 prevX = point.canvasx;
867 }
868 }
869 ctx.fill();
870 }
871 ctx.restore();
872 }
873
874 // Drawing the lines.
875 for (i = 0; i < setCount; i += 1) {
876 this._drawLine(ctx, i);
877 }
878 };
879
880 /**
881 * This does dashed lines onto a canvas for a given pattern. You must call
882 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
883 * the state of the line in regards to where we left off on drawing the pattern.
884 * You can draw a dashed line in several function calls and the pattern will be
885 * continous as long as you didn't call this function with a different pattern
886 * in between.
887 * @param ctx The canvas 2d context to draw on.
888 * @param x The start of the line's x coordinate.
889 * @param y The start of the line's y coordinate.
890 * @param x2 The end of the line's x coordinate.
891 * @param y2 The end of the line's y coordinate.
892 * @param pattern The dash pattern to draw, an array of integers where even
893 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
894 * is drawn, 2 is the space between.). A null pattern, array of length one, or
895 * empty array will do just a solid line.
896 * @private
897 */
898 DygraphCanvasRenderer.prototype._dashedLine = function(ctx, x, y, x2, y2, pattern) {
899 // Original version http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
900 // Modified by Russell Valentine to keep line history and continue the pattern
901 // where it left off.
902 var dx, dy, len, rot, patternIndex, segment;
903
904 // If we don't have a pattern or it is an empty array or of size one just
905 // do a solid line.
906 if (!pattern || pattern.length <= 1) {
907 ctx.moveTo(x, y);
908 ctx.lineTo(x2, y2);
909 return;
910 }
911
912 // If we have a different dash pattern than the last time this was called we
913 // reset our dash history and start the pattern from the begging
914 // regardless of state of the last pattern.
915 if (!Dygraph.compareArrays(pattern, this._dashedLineToHistoryPattern)) {
916 this._dashedLineToHistoryPattern = pattern;
917 this._dashedLineToHistory = [0, 0];
918 }
919 ctx.save();
920
921 // Calculate transformation parameters
922 dx = (x2-x);
923 dy = (y2-y);
924 len = Math.sqrt(dx*dx + dy*dy);
925 rot = Math.atan2(dy, dx);
926
927 // Set transformation
928 ctx.translate(x, y);
929 ctx.moveTo(0, 0);
930 ctx.rotate(rot);
931
932 // Set last pattern index we used for this pattern.
933 patternIndex = this._dashedLineToHistory[0];
934 x = 0;
935 while (len > x) {
936 // Get the length of the pattern segment we are dealing with.
937 segment = pattern[patternIndex];
938 // If our last draw didn't complete the pattern segment all the way we
939 // will try to finish it. Otherwise we will try to do the whole segment.
940 if (this._dashedLineToHistory[1]) {
941 x += this._dashedLineToHistory[1];
942 } else {
943 x += segment;
944 }
945 if (x > len) {
946 // We were unable to complete this pattern index all the way, keep
947 // where we are the history so our next draw continues where we left off
948 // in the pattern.
949 this._dashedLineToHistory = [patternIndex, x-len];
950 x = len;
951 } else {
952 // We completed this patternIndex, we put in the history that we are on
953 // the beginning of the next segment.
954 this._dashedLineToHistory = [(patternIndex+1)%pattern.length, 0];
955 }
956
957 // We do a line on a even pattern index and just move on a odd pattern index.
958 // The move is the empty space in the dash.
959 if(patternIndex % 2 === 0) {
960 ctx.lineTo(x, 0);
961 } else {
962 ctx.moveTo(x, 0);
963 }
964 // If we are not done, next loop process the next pattern segment, or the
965 // first segment again if we are at the end of the pattern.
966 patternIndex = (patternIndex+1) % pattern.length;
967 }
968 ctx.restore();
969 };