Merge pull request #673 from danvk/track-code-size
[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 this.scale = canvas.width / dygraph.width_;
21 };
22
23 /**
24 * @param {number} x The screen x-coordinate at which to sample.
25 * @param {number} y The screen y-coordinate at which to sample.
26 * @return {Array.<number>} a 4D array: [R, G, B, alpha]. All four values
27 * are in [0, 255]. A pixel which has never been touched will be [0,0,0,0].
28 */
29 PixelSampler.prototype.colorAtPixel = function(x, y) {
30 var i = 4 * (x * this.scale + this.imageData_.width * y * this.scale);
31 var d = this.imageData_.data;
32 return [d[i], d[i+1], d[i+2], d[i+3]];
33 };
34
35 /**
36 * The method samples a color using data coordinates (not screen coordinates).
37 * This will round your data coordinates to the nearest screen pixel before
38 * sampling.
39 * @param {number} x The data x-coordinate at which to sample.
40 * @param {number} y The data y-coordinate at which to sample.
41 * @return {Array.<number>} a 4D array: [R, G, B, alpha]. All four values
42 * are in [0, 255]. A pixel which has never been touched will be [0,0,0,0].
43 */
44 PixelSampler.prototype.colorAtCoordinate = function(x, y) {
45 var dom_xy = this.dygraph_.toDomCoords(x, y);
46 return this.colorAtPixel(Math.round(dom_xy[0]), Math.round(dom_xy[1]));
47 };