Merge pull request #271 from danvk/connect-separated-points
[dygraphs.git] / auto_tests / tests / PixelSampler.js
1 // Copyright 2012 Google Inc. All Rights Reserved.
2
3 /**
4 * @fileoverview A class to facilitate sampling colors at particular pixels on a
5 * dygraph.
6 * @author danvk@google.com (Dan Vanderkam)
7 */
8
9 'use strict';
10
11 /**
12 * @constructor
13 */
14 var PixelSampler = function(dygraph) {
15 this.dygraph_ = dygraph;
16
17 var canvas = dygraph.hidden_;
18 var ctx = canvas.getContext("2d");
19 this.imageData_ = ctx.getImageData(0, 0, canvas.width, canvas.height);
20 };
21
22 /**
23 * @param {number} x The screen x-coordinate at which to sample.
24 * @param {number} y The screen y-coordinate at which to sample.
25 * @return {Array.<number>} a 4D array: [R, G, B, alpha]. All four values
26 * are in [0, 255]. A pixel which has never been touched will be [0,0,0,0].
27 */
28 PixelSampler.prototype.colorAtPixel = function(x, y) {
29 var i = 4 * (x + this.imageData_.width * y);
30 var d = this.imageData_.data;
31 return [d[i], d[i+1], d[i+2], d[i+3]];
32 };
33
34 /**
35 * The method samples a color using data coordinates (not screen coordinates).
36 * This will round your data coordinates to the nearest screen pixel before
37 * sampling.
38 * @param {number} x The data x-coordinate at which to sample.
39 * @param {number} y The data y-coordinate at which to sample.
40 * @return {Array.<number>} a 4D array: [R, G, B, alpha]. All four values
41 * are in [0, 255]. A pixel which has never been touched will be [0,0,0,0].
42 */
43 PixelSampler.prototype.colorAtCoordinate = function(x, y) {
44 var dom_xy = this.dygraph_.toDomCoords(x, y);
45 return this.colorAtPixel(Math.round(dom_xy[0]), Math.round(dom_xy[1]));
46 };