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