Merge branch 'PR723'
[dygraphs.git] / src / extras / crosshair.js
... / ...
CommitLineData
1/**
2 * @license
3 * Copyright 2015 Petr Shevtsov (petr.shevtsov@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7/*global Dygraph:false */
8/*jshint globalstrict: true */
9Dygraph.Plugins.Crosshair = (function() {
10 "use strict";
11
12 /**
13 * Creates the crosshair
14 *
15 * @constructor
16 */
17
18 var crosshair = function(opt_options) {
19 this.canvas_ = document.createElement("canvas");
20 opt_options = opt_options || {};
21 this.direction_ = opt_options.direction || null;
22 };
23
24 crosshair.prototype.toString = function() {
25 return "Crosshair Plugin";
26 };
27
28 /**
29 * @param {Dygraph} g Graph instance.
30 * @return {object.<string, function(ev)>} Mapping of event names to callbacks.
31 */
32 crosshair.prototype.activate = function(g) {
33 g.graphDiv.appendChild(this.canvas_);
34
35 return {
36 select: this.select,
37 deselect: this.deselect
38 };
39 };
40
41 crosshair.prototype.select = function(e) {
42 if (this.direction_ === null) {
43 return;
44 }
45
46 var width = e.dygraph.width_;
47 var height = e.dygraph.height_;
48 this.canvas_.width = width;
49 this.canvas_.height = height;
50 this.canvas_.style.width = width + "px"; // for IE
51 this.canvas_.style.height = height + "px"; // for IE
52
53 var ctx = this.canvas_.getContext("2d");
54 ctx.clearRect(0, 0, width, height);
55 ctx.strokeStyle = "rgba(0, 0, 0,0.3)";
56 ctx.beginPath();
57
58 var canvasx = Math.floor(e.dygraph.selPoints_[0].canvasx) + 0.5; // crisper rendering
59
60 if (this.direction_ === "vertical" || this.direction_ === "both") {
61 ctx.moveTo(canvasx, 0);
62 ctx.lineTo(canvasx, height);
63 }
64
65 if (this.direction_ === "horizontal" || this.direction_ === "both") {
66 for (var i = 0; i < e.dygraph.selPoints_.length; i++) {
67 var canvasy = Math.floor(e.dygraph.selPoints_[i].canvasy) + 0.5; // crisper rendering
68 ctx.moveTo(0, canvasy);
69 ctx.lineTo(width, canvasy);
70 }
71 }
72
73 ctx.stroke();
74 ctx.closePath();
75 };
76
77 crosshair.prototype.deselect = function(e) {
78 var ctx = this.canvas_.getContext("2d");
79 ctx.clearRect(0, 0, this.canvas_.width, this.canvas_.height);
80 };
81
82 crosshair.prototype.destroy = function() {
83 this.canvas_ = null;
84 };
85
86 return crosshair;
87})();