3 * Copyright 2012 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
6 /*global Dygraph:false */
8 Dygraph.Plugins.Grid = (function() {
12 Current bits of jankiness:
13 - Direct layout access
22 * Draws the gridlines, i.e. the gray horizontal & vertical lines running the
23 * length of the chart.
27 var grid = function() {
30 grid.prototype.toString = function() {
31 return "Gridline Plugin";
34 grid.prototype.activate = function(g) {
36 willDrawChart: this.willDrawChart
40 grid.prototype.willDrawChart = function(e) {
41 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
42 // half-integers. This prevents them from drawing in two rows/cols.
44 var ctx = e.drawingContext;
45 var layout = g.layout_;
46 var area = e.dygraph.plotter_.area;
48 function halfUp(x) { return Math.round(x) + 0.5; }
49 function halfDown(y){ return Math.round(y) - 0.5; }
52 if (g.getOption('drawYGrid')) {
53 var axes = ["y", "y2"];
54 var strokeStyles = [], lineWidths = [], drawGrid = [], stroking = [], strokePattern = [];
55 for (var i = 0; i < axes.length; i++) {
56 drawGrid[i] = g.getOptionForAxis("drawGrid", axes[i]);
58 strokeStyles[i] = g.getOptionForAxis('gridLineColor', axes[i]);
59 lineWidths[i] = g.getOptionForAxis('gridLineWidth', axes[i]);
60 strokePattern[i] = g.getOptionForAxis('gridLinePattern', axes[i]);
61 stroking[i] = strokePattern[i] && (strokePattern[i].length >= 2);
64 ticks = layout.yticks;
66 // draw grids for the different y axes
67 for (i = 0; i < ticks.length; i++) {
68 var axis = ticks[i][0];
71 ctx.installPattern(strokePattern[axis]);
73 ctx.strokeStyle = strokeStyles[axis];
74 ctx.lineWidth = lineWidths[axis];
77 y = halfDown(area.y + ticks[i][1] * area.h);
80 ctx.lineTo(x + area.w, y);
85 ctx.uninstallPattern();
92 // draw grid for x axis
93 if (g.getOption('drawXGrid') && g.getOptionForAxis("drawGrid", 'x')) {
94 ticks = layout.xticks;
96 var strokePattern = g.getOptionForAxis('gridLinePattern', 'x');
97 var stroking = strokePattern && (strokePattern.length >= 2);
99 ctx.installPattern(strokePattern);
101 ctx.strokeStyle = g.getOptionForAxis('gridLineColor', 'x');
102 ctx.lineWidth = g.getOptionForAxis('gridLineWidth', 'x');
103 for (i = 0; i < ticks.length; i++) {
104 x = halfUp(area.x + ticks[i][0] * area.w);
105 y = halfDown(area.y + area.h);
108 ctx.lineTo(x, area.y);
113 ctx.uninstallPattern();
119 grid.prototype.destroy = function() {