Checkpoint: annotations fully ported to plugin system. All tests pass.
[dygraphs.git] / dygraph-canvas.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6a1aa64f
DV
6
7/**
74a5af31
DV
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
3df0ccf0 11 * In particular, support for:
0abfbd7e 12 * - grid overlays
3df0ccf0
DV
13 * - error bars
14 * - dygraphs attribute system
6a1aa64f
DV
15 */
16
6a1aa64f 17/**
423f5ed3
DV
18 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
19 * a canvas. It's based on PlotKit.CanvasRenderer.
6a1aa64f 20 * @param {Object} element The canvas to attach to
2cf95fff
RK
21 * @param {Object} elementContext The 2d context of the canvas (injected so it
22 * can be mocked for testing.)
285a6bda 23 * @param {Layout} layout The DygraphLayout object for this graph.
74a5af31 24 * @constructor
6a1aa64f 25 */
c0f54d4f 26
758a629f
DV
27/*jshint globalstrict: true */
28/*global Dygraph:false,RGBColor:false */
c0f54d4f
DV
29"use strict";
30
79253bd0 31
8cfe592f
DV
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 */
c0f54d4f 49var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
9317362d 50 this.dygraph_ = dygraph;
fbe31dc8 51
fbe31dc8 52 this.layout = layout;
b0c3b730 53 this.element = element;
2cf95fff 54 this.elementContext = elementContext;
fbe31dc8
DV
55 this.container = this.element.parentNode;
56
fbe31dc8
DV
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
758a629f
DV
65 this.xlabels = [];
66 this.ylabels = [];
67 this.annotations = [];
fbe31dc8 68
70be5ed1 69 this.area = layout.getPlotArea();
423f5ed3
DV
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.
920208fb
PF
75 if (this.dygraph_.isUsingExcanvas_) {
76 this._createIEClipArea();
77 } else {
971870e5
DV
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();
920208fb 85
971870e5
DV
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 }
920208fb 91 }
423f5ed3
DV
92};
93
94DygraphCanvasRenderer.prototype.attr_ = function(x) {
95 return this.dygraph_.attr_(x);
96};
97
8cfe592f
DV
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 */
fbe31dc8 104DygraphCanvasRenderer.prototype.clear = function() {
758a629f 105 var context;
fbe31dc8
DV
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 }
758a629f 113 context = this.elementContext;
fbe31dc8
DV
114 }
115 catch (e) {
76171648 116 // TODO(danvk): this is broken, since MochiKit.Async is gone.
758a629f
DV
117 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
118 // this.clearDelay.addCallback(bind(this.clear, this));
fbe31dc8
DV
119 return;
120 }
121 }
122
758a629f 123 context = this.elementContext;
fbe31dc8
DV
124 context.clearRect(0, 0, this.width, this.height);
125
758a629f
DV
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 }
ce49c2fa 131 }
758a629f
DV
132
133 removeArray(this.xlabels);
134 removeArray(this.ylabels);
135 removeArray(this.annotations);
136
758a629f
DV
137 this.xlabels = [];
138 this.ylabels = [];
139 this.annotations = [];
fbe31dc8
DV
140};
141
8cfe592f
DV
142/**
143 * Checks whether the browser supports the &lt;canvas&gt; tag.
144 * @private
145 */
fbe31dc8
DV
146DygraphCanvasRenderer.isSupported = function(canvasName) {
147 var canvas = null;
148 try {
758a629f 149 if (typeof(canvasName) == 'undefined' || canvasName === null) {
b0c3b730 150 canvas = document.createElement("canvas");
758a629f 151 } else {
b0c3b730 152 canvas = canvasName;
758a629f
DV
153 }
154 canvas.getContext("2d");
fbe31dc8
DV
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;
6a1aa64f 164};
6a1aa64f
DV
165
166/**
600d841a
DV
167 * @param { [String] } colors Array of color strings. Should have one entry for
168 * each series to be rendered.
169 */
170DygraphCanvasRenderer.prototype.setColors = function(colors) {
171 this.colorScheme_ = colors;
172};
173
174/**
8cfe592f
DV
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
6a1aa64f 180 */
285a6bda 181DygraphCanvasRenderer.prototype.render = function() {
528ce7e5
DV
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.
2cf95fff 184 var ctx = this.elementContext;
758a629f
DV
185 function halfUp(x) { return Math.round(x) + 0.5; }
186 function halfDown(y){ return Math.round(y) - 0.5; }
e7746234 187
423f5ed3 188 if (this.attr_('underlayCallback')) {
1e41bd2d
DV
189 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
190 // users who expect a deprecated form of this callback.
423f5ed3 191 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
e7746234
EC
192 }
193
758a629f 194 var x, y, i, ticks;
423f5ed3 195 if (this.attr_('drawYGrid')) {
758a629f 196 ticks = this.layout.yticks;
bbba718a 197 // TODO(konigsberg): I don't think these calls to save() have a corresponding restore().
6a1aa64f 198 ctx.save();
423f5ed3 199 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 200 ctx.lineWidth = this.attr_('gridLineWidth');
758a629f 201 for (i = 0; i < ticks.length; i++) {
880a574f 202 // TODO(danvk): allow secondary axes to draw a grid, too.
758a629f
DV
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);
6a1aa64f
DV
206 ctx.beginPath();
207 ctx.moveTo(x, y);
208 ctx.lineTo(x + this.area.w, y);
209 ctx.closePath();
210 ctx.stroke();
211 }
6bf4df7f 212 ctx.restore();
6a1aa64f
DV
213 }
214
423f5ed3 215 if (this.attr_('drawXGrid')) {
758a629f 216 ticks = this.layout.xticks;
6a1aa64f 217 ctx.save();
423f5ed3 218 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 219 ctx.lineWidth = this.attr_('gridLineWidth');
758a629f
DV
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);
6a1aa64f 223 ctx.beginPath();
880a574f 224 ctx.moveTo(x, y);
6a1aa64f
DV
225 ctx.lineTo(x, this.area.y);
226 ctx.closePath();
227 ctx.stroke();
228 }
6bf4df7f 229 ctx.restore();
6a1aa64f 230 }
2ce09b19
DV
231
232 // Do the ordinary rendering, as before
2ce09b19 233 this._renderLineChart();
fbe31dc8
DV
234 this._renderAxis();
235};
236
920208fb
PF
237DygraphCanvasRenderer.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) {
758a629f 261 if (area.w === 0 || area.h === 0) {
920208fb
PF
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
758a629f
DV
277 createClipDiv({
278 x:0, y:0,
279 w:plotArea.x,
280 h:this.height
281 });
282
920208fb 283 // Top
758a629f
DV
284 createClipDiv({
285 x: plotArea.x, y: 0,
286 w: this.width - plotArea.x,
287 h: plotArea.y
288 });
289
920208fb 290 // Right side
758a629f
DV
291 createClipDiv({
292 x: plotArea.x + plotArea.w, y: 0,
293 w: this.width-plotArea.x - plotArea.w,
294 h: this.height
295 });
296
920208fb 297 // Bottom
758a629f
DV
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};
fbe31dc8
DV
305
306DygraphCanvasRenderer.prototype._renderAxis = function() {
423f5ed3 307 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
fbe31dc8 308
528ce7e5 309 // Round pixels to half-integer boundaries for crisper drawing.
758a629f
DV
310 function halfUp(x) { return Math.round(x) + 0.5; }
311 function halfDown(y){ return Math.round(y) - 0.5; }
528ce7e5 312
2cf95fff 313 var context = this.elementContext;
fbe31dc8 314
758a629f
DV
315 var label, x, y, tick, i;
316
34fedff8 317 var labelStyle = {
423f5ed3
DV
318 position: "absolute",
319 fontSize: this.attr_('axisLabelFontSize') + "px",
320 zIndex: 10,
321 color: this.attr_('axisLabelColor'),
322 width: this.attr_('axisLabelWidth') + "px",
74a5af31 323 // height: this.attr_('axisLabelFontSize') + 2 + "px",
758a629f 324 lineHeight: "normal", // Something other than "normal" line-height screws up label positioning.
423f5ed3 325 overflow: "hidden"
34fedff8 326 };
48e614ac 327 var makeDiv = function(txt, axis, prec_axis) {
34fedff8
DV
328 var div = document.createElement("div");
329 for (var name in labelStyle) {
85b99f0b
DV
330 if (labelStyle.hasOwnProperty(name)) {
331 div.style[name] = labelStyle[name];
332 }
fbe31dc8 333 }
ba451526 334 var inner_div = document.createElement("div");
48e614ac
DV
335 inner_div.className = 'dygraph-axis-label' +
336 ' dygraph-axis-label-' + axis +
337 (prec_axis ? ' dygraph-axis-label-' + prec_axis : '');
3bdf7140 338 inner_div.innerHTML=txt;
ba451526 339 div.appendChild(inner_div);
34fedff8 340 return div;
fbe31dc8
DV
341 };
342
343 // axis lines
344 context.save();
423f5ed3
DV
345 context.strokeStyle = this.attr_('axisLineColor');
346 context.lineWidth = this.attr_('axisLineWidth');
fbe31dc8 347
423f5ed3 348 if (this.attr_('drawYAxis')) {
8b7a0cc3 349 if (this.layout.yticks && this.layout.yticks.length > 0) {
48e614ac 350 var num_axes = this.dygraph_.numAxes();
758a629f
DV
351 for (i = 0; i < this.layout.yticks.length; i++) {
352 tick = this.layout.yticks[i];
fbe31dc8 353 if (typeof(tick) == "function") return;
758a629f 354 x = this.area.x;
880a574f 355 var sgn = 1;
48e614ac 356 var prec_axis = 'y1';
880a574f
DV
357 if (tick[0] == 1) { // right-side y-axis
358 x = this.area.x + this.area.w;
359 sgn = -1;
48e614ac 360 prec_axis = 'y2';
9012dd21 361 }
758a629f 362 y = this.area.y + tick[1] * this.area.h;
920208fb
PF
363
364 /* Tick marks are currently clipped, so don't bother drawing them.
fbe31dc8 365 context.beginPath();
528ce7e5 366 context.moveTo(halfUp(x), halfDown(y));
0e23cfc6 367 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
fbe31dc8
DV
368 context.closePath();
369 context.stroke();
920208fb 370 */
fbe31dc8 371
758a629f 372 label = makeDiv(tick[2], 'y', num_axes == 2 ? prec_axis : null);
423f5ed3 373 var top = (y - this.attr_('axisLabelFontSize') / 2);
fbe31dc8
DV
374 if (top < 0) top = 0;
375
423f5ed3 376 if (top + this.attr_('axisLabelFontSize') + 3 > this.height) {
fbe31dc8
DV
377 label.style.bottom = "0px";
378 } else {
379 label.style.top = top + "px";
380 }
758a629f 381 if (tick[0] === 0) {
423f5ed3 382 label.style.left = (this.area.x - this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
9012dd21
DV
383 label.style.textAlign = "right";
384 } else if (tick[0] == 1) {
385 label.style.left = (this.area.x + this.area.w +
423f5ed3 386 this.attr_('axisTickSize')) + "px";
9012dd21
DV
387 label.style.textAlign = "left";
388 }
423f5ed3 389 label.style.width = this.attr_('yAxisLabelWidth') + "px";
b0c3b730 390 this.container.appendChild(label);
fbe31dc8 391 this.ylabels.push(label);
2160ed4a 392 }
fbe31dc8
DV
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];
423f5ed3 398 var fontSize = this.attr_('axisLabelFontSize');
758a629f 399 var bottom = parseInt(bottomTick.style.top, 10) + fontSize;
fbe31dc8 400 if (bottom > this.height - fontSize) {
758a629f 401 bottomTick.style.top = (parseInt(bottomTick.style.top, 10) -
fbe31dc8
DV
402 fontSize / 2) + "px";
403 }
404 }
405
528ce7e5 406 // draw a vertical line on the left to separate the chart from the labels.
f4b87da2
KW
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 }
fbe31dc8 415 context.beginPath();
f4b87da2
KW
416 context.moveTo(axisX, halfDown(this.area.y));
417 context.lineTo(axisX, halfDown(this.area.y + this.area.h));
fbe31dc8
DV
418 context.closePath();
419 context.stroke();
c1dbeb10 420
528ce7e5 421 // if there's a secondary y-axis, draw a vertical line for that, too.
c1dbeb10
DV
422 if (this.dygraph_.numAxes() == 2) {
423 context.beginPath();
528ce7e5
DV
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));
c1dbeb10
DV
426 context.closePath();
427 context.stroke();
428 }
fbe31dc8
DV
429 }
430
423f5ed3 431 if (this.attr_('drawXAxis')) {
fbe31dc8 432 if (this.layout.xticks) {
758a629f
DV
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;
920208fb
PF
437
438 /* Tick marks are currently clipped, so don't bother drawing them.
fbe31dc8 439 context.beginPath();
528ce7e5 440 context.moveTo(halfUp(x), halfDown(y));
423f5ed3 441 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
fbe31dc8
DV
442 context.closePath();
443 context.stroke();
920208fb 444 */
fbe31dc8 445
758a629f 446 label = makeDiv(tick[1], 'x');
fbe31dc8 447 label.style.textAlign = "center";
423f5ed3 448 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
fbe31dc8 449
423f5ed3
DV
450 var left = (x - this.attr_('axisLabelWidth')/2);
451 if (left + this.attr_('axisLabelWidth') > this.width) {
452 left = this.width - this.attr_('xAxisLabelWidth');
fbe31dc8
DV
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";
423f5ed3 461 label.style.width = this.attr_('xAxisLabelWidth') + "px";
b0c3b730 462 this.container.appendChild(label);
fbe31dc8 463 this.xlabels.push(label);
2160ed4a 464 }
fbe31dc8
DV
465 }
466
467 context.beginPath();
f4b87da2
KW
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);
fbe31dc8
DV
478 context.closePath();
479 context.stroke();
480 }
481
482 context.restore();
6a1aa64f
DV
483};
484
fbe31dc8 485
ccb0001c 486/**
8722284b
RK
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.
ccb0001c 491 */
8722284b
RK
492DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
493 return connectSeparatedPoints ? DygraphCanvasRenderer._predicateThatSkipsEmptyPoints : null;
494}
495
496DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
497 function(array, idx) { return array[idx].yval !== null; }
04c104d7 498
857a6931 499DygraphCanvasRenderer.prototype._drawStyledLine = function(
5469113b
KW
500 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
501 drawPointCallback, pointSize) {
99a77a04 502 // TODO(konigsberg): Compute attributes outside this method call.
857a6931
KW
503 var stepPlot = this.attr_("stepPlot");
504 var firstIndexInSet = this.layout.setPointsOffsets[i];
505 var setLength = this.layout.setPointsLengths[i];
857a6931 506 var points = this.layout.points;
857a6931
KW
507 if (!Dygraph.isArrayLike(strokePattern)) {
508 strokePattern = null;
509 }
a5a50727 510 var drawGapPoints = this.dygraph_.attr_('drawGapEdgePoints', setName);
857a6931 511
b843b52c 512 ctx.save();
7d1afbb9 513
7d1afbb9 514 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
8722284b 515 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
7d1afbb9 516
31f8e58b
RK
517 var pointsOnLine;
518 var strategy;
519 if (!strokePattern || strokePattern.length <= 1) {
520 strategy = trivialStrategy(ctx, color, strokeWidth);
b843b52c 521 } else {
31f8e58b 522 strategy = nonTrivialStrategy(this, ctx, color, strokeWidth, strokePattern);
b843b52c 523 }
31f8e58b
RK
524 pointsOnLine = this._drawSeries(ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, strategy);
525 this._drawPointsOnLine(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize);
526
b843b52c
RK
527 ctx.restore();
528};
529
31f8e58b
RK
530var 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
553var 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
a401ca8a
RK
576DygraphCanvasRenderer.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
31f8e58b
RK
586DygraphCanvasRenderer.prototype._drawSeries = function(
587 ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints,
588 stepPlot, strategy) {
589
31f8e58b
RK
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
b843b52c 595 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
31f8e58b
RK
596 var first = true; // the first cycle through the while loop
597
598 strategy.init();
599
7d1afbb9
RK
600 while(iter.hasNext()) {
601 point = iter.next();
a02978e2 602 if (point.canvasy === null || point.canvasy != point.canvasy) {
31f8e58b 603 if (stepPlot && prevCanvasX !== null) {
857a6931 604 // Draw a horizontal line to the start of the missing data
31f8e58b
RK
605 strategy.startSegment();
606 strategy.drawLine(prevX, prevY, point.canvasx, prevY);
607 strategy.endSegment();
857a6931 608 }
31f8e58b 609 prevCanvasX = prevCanvasY = null;
857a6931 610 } else {
31f8e58b 611 nextCanvasY = iter.hasNext() ? iter.peek().canvasy : null;
a02978e2
RK
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);
19b84fe7 616 if (drawGapPoints) {
31f8e58b 617 // Also consider a point to be "isolated" if it's adjacent to a
19b84fe7 618 // null point, excluding the graph edges.
31f8e58b 619 if ((!first && !prevCanvasX) ||
a02978e2 620 (iter.hasNext() && isNextCanvasYNullOrNaN)) {
19b84fe7
KW
621 isIsolated = true;
622 }
623 }
31f8e58b
RK
624 if (prevCanvasX !== null) {
625 if (strategy.skipPixel(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy)) {
857a6931
KW
626 continue;
627 }
857a6931 628 if (strokeWidth) {
31f8e58b 629 strategy.startSegment();
857a6931 630 if (stepPlot) {
31f8e58b
RK
631 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, prevCanvasY);
632 prevCanvasX = point.canvasx;
857a6931 633 }
31f8e58b
RK
634 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy);
635 strategy.endSegment();
b843b52c
RK
636 }
637 }
b843b52c
RK
638 if (drawPoints || isIsolated) {
639 pointsOnLine.push([point.canvasx, point.canvasy]);
640 }
31f8e58b
RK
641 prevCanvasX = point.canvasx;
642 prevCanvasY = point.canvasy;
b843b52c 643 }
7d1afbb9 644 first = false;
b843b52c 645 }
31f8e58b
RK
646 strategy.finish();
647 return pointsOnLine;
857a6931
KW
648};
649
650DygraphCanvasRenderer.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);
5469113b
KW
656 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
657 Dygraph.Circles.DEFAULT;
99a77a04 658
857a6931 659 if (borderWidth && strokeWidth) {
5469113b 660 this._drawStyledLine(ctx, i, setName,
857a6931
KW
661 this.dygraph_.attr_("strokeBorderColor", setName),
662 strokeWidth + 2 * borderWidth,
663 this.dygraph_.attr_("strokePattern", setName),
664 this.dygraph_.attr_("drawPoints", setName),
5469113b 665 drawPointCallback,
857a6931
KW
666 this.dygraph_.attr_("pointSize", setName));
667 }
668
5469113b 669 this._drawStyledLine(ctx, i, setName,
857a6931
KW
670 this.colors[setName],
671 strokeWidth,
672 this.dygraph_.attr_("strokePattern", setName),
673 this.dygraph_.attr_("drawPoints", setName),
5469113b 674 drawPointCallback,
857a6931
KW
675 this.dygraph_.attr_("pointSize", setName));
676};
ce49c2fa 677
6a1aa64f 678/**
758a629f
DV
679 * Actually draw the lines chart, including error bars.
680 * TODO(danvk): split this into several smaller functions.
681 * @private
6a1aa64f 682 */
285a6bda 683DygraphCanvasRenderer.prototype._renderLineChart = function() {
44c6bc29 684 // TODO(danvk): use this.attr_ for many of these.
857a6931 685 var ctx = this.elementContext;
423f5ed3 686 var fillAlpha = this.attr_('fillAlpha');
e4182459 687 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
44c6bc29 688 var fillGraph = this.attr_("fillGraph");
b2c9222a
DV
689 var stackedGraph = this.attr_("stackedGraph");
690 var stepPlot = this.attr_("stepPlot");
c3e1495b
AR
691 var points = this.layout.points;
692 var pointsLength = points.length;
8722284b 693 var point, i, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis;
21d3323f 694
82c6fe4d 695 var setNames = this.layout.setNames;
21d3323f 696 var setCount = setNames.length;
6a1aa64f 697
ee53deb9 698 this.colors = this.dygraph_.colorsMap_;
f032c51d 699
ff00d3e2
DV
700 // Update Points
701 // TODO(danvk): here
b843b52c
RK
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.
758a629f
DV
706 for (i = pointsLength; i--;) {
707 point = points[i];
6a1aa64f
DV
708 point.canvasx = this.area.w * point.x + this.area.x;
709 point.canvasy = this.area.h * point.y + this.area.y;
710 }
6a1aa64f
DV
711
712 // create paths
80aaae18 713 if (errorBars) {
857a6931 714 ctx.save();
6a834bbb
DV
715 if (fillGraph) {
716 this.dygraph_.warn("Can't use fillGraph option with error bars");
717 }
718
758a629f
DV
719 for (i = 0; i < setCount; i++) {
720 setName = setNames[i];
721 axis = this.dygraph_.axisPropertiesForSeries(setName);
722 color = this.colors[setName];
6a1aa64f 723
04c104d7
KW
724 var firstIndexInSet = this.layout.setPointsOffsets[i];
725 var setLength = this.layout.setPointsLengths[i];
04c104d7 726
8722284b
RK
727 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
728 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
04c104d7 729
6a1aa64f 730 // setup graphics context
758a629f
DV
731 prevX = NaN;
732 prevY = NaN;
733 prevYs = [-1, -1];
734 yscale = axis.yscale;
f474c2a3 735 // should be same color as the lines but only 15% opaque.
758a629f
DV
736 rgb = new RGBColor(color);
737 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
43af96e7 738 fillAlpha + ')';
f474c2a3 739 ctx.fillStyle = err_color;
05c9d0c4 740 ctx.beginPath();
8722284b
RK
741 while (iter.hasNext()) {
742 point = iter.next();
04c104d7 743 if (point.name == setName) { // TODO(klausw): this is always true
e9fe4a2f 744 if (!Dygraph.isOK(point.y)) {
56623f3b 745 prevX = NaN;
ae85914a 746 continue;
5011e7a1 747 }
ce49c2fa 748
3637724f 749 // TODO(danvk): here
afdc483f 750 if (stepPlot) {
758a629f 751 newYs = [ point.y_bottom, point.y_top ];
afdc483f
NN
752 prevY = point.y;
753 } else {
758a629f 754 newYs = [ point.y_bottom, point.y_top ];
afdc483f 755 }
6a1aa64f
DV
756 newYs[0] = this.area.h * newYs[0] + this.area.y;
757 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 758 if (!isNaN(prevX)) {
afdc483f 759 if (stepPlot) {
47600757 760 ctx.moveTo(prevX, newYs[0]);
afdc483f 761 } else {
47600757 762 ctx.moveTo(prevX, prevYs[0]);
afdc483f 763 }
5954ef32
DV
764 ctx.lineTo(point.canvasx, newYs[0]);
765 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 766 if (stepPlot) {
47600757 767 ctx.lineTo(prevX, newYs[1]);
afdc483f 768 } else {
47600757 769 ctx.lineTo(prevX, prevYs[1]);
afdc483f 770 }
5954ef32
DV
771 ctx.closePath();
772 }
354e15ab 773 prevYs = newYs;
5954ef32
DV
774 prevX = point.canvasx;
775 }
776 }
777 ctx.fill();
778 }
857a6931 779 ctx.restore();
5954ef32 780 } else if (fillGraph) {
857a6931 781 ctx.save();
349dd9ba
DW
782 var baseline = {}; // for stacked graphs: baseline for filling
783 var currBaseline;
354e15ab
DE
784
785 // process sets in reverse order (needed for stacked graphs)
758a629f
DV
786 for (i = setCount - 1; i >= 0; i--) {
787 setName = setNames[i];
788 color = this.colors[setName];
789 axis = this.dygraph_.axisPropertiesForSeries(setName);
ea4942ed
DV
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;
04c104d7
KW
794 var firstIndexInSet = this.layout.setPointsOffsets[i];
795 var setLength = this.layout.setPointsLengths[i];
04c104d7 796
8722284b
RK
797 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
798 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
5954ef32
DV
799
800 // setup graphics context
758a629f
DV
801 prevX = NaN;
802 prevYs = [-1, -1];
803 yscale = axis.yscale;
5954ef32 804 // should be same color as the lines but only 15% opaque.
758a629f
DV
805 rgb = new RGBColor(color);
806 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
43af96e7 807 fillAlpha + ')';
5954ef32
DV
808 ctx.fillStyle = err_color;
809 ctx.beginPath();
8722284b
RK
810 while(iter.hasNext()) {
811 point = iter.next();
04c104d7 812 if (point.name == setName) { // TODO(klausw): this is always true
e9fe4a2f 813 if (!Dygraph.isOK(point.y)) {
56623f3b 814 prevX = NaN;
5954ef32
DV
815 continue;
816 }
354e15ab 817 if (stackedGraph) {
349dd9ba
DW
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 }
354e15ab 829 newYs = [ point.canvasy, lastY ];
b843b52c 830
349dd9ba
DW
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 }
b843b52c 842
354e15ab
DE
843 } else {
844 newYs = [ point.canvasy, axisY ];
845 }
56623f3b 846 if (!isNaN(prevX)) {
05c9d0c4 847 ctx.moveTo(prevX, prevYs[0]);
b843b52c 848
afdc483f 849 if (stepPlot) {
47600757 850 ctx.lineTo(point.canvasx, prevYs[0]);
349dd9ba
DW
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 }
afdc483f 857 } else {
47600757 858 ctx.lineTo(point.canvasx, newYs[0]);
349dd9ba 859 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 860 }
b843b52c 861
05c9d0c4
DV
862 ctx.lineTo(prevX, prevYs[1]);
863 ctx.closePath();
6a1aa64f 864 }
354e15ab 865 prevYs = newYs;
6a1aa64f
DV
866 prevX = point.canvasx;
867 }
05c9d0c4 868 }
6a1aa64f
DV
869 ctx.fill();
870 }
857a6931 871 ctx.restore();
80aaae18
DV
872 }
873
f9414b11 874 // Drawing the lines.
758a629f 875 for (i = 0; i < setCount; i += 1) {
857a6931 876 this._drawLine(ctx, i);
80aaae18 877 }
6a1aa64f 878};
79253bd0 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 */
898DygraphCanvasRenderer.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};