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