d45ab8a30e681fcb1a8d0a0626de8af2b29a08f4
1 // Copyright 2012 Google Inc. All Rights Reserved.
4 * @fileoverview A class to facilitate sampling colors at particular pixels on a
6 * @author danvk@google.com (Dan Vanderkam)
14 var PixelSampler
= function(dygraph
) {
15 this.dygraph_
= dygraph
;
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_
;
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].
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]];
36 * Convenience wrapper around colorAtPixel if you only care about RGB (not A).
37 * @param {number} x The screen x-coordinate at which to sample.
38 * @param {number} y The screen y-coordinate at which to sample.
39 * @return {Array.<number>} a 3D array: [R, G, B]. All three values
40 * are in [0, 255]. A pixel which has never been touched will be [0,0,0].
42 PixelSampler
.prototype.rgbAtPixel
= function(x
, y
) {
43 return this.colorAtPixel(x
, y
).slice(0, 3);
47 * The method samples a color using data coordinates (not screen coordinates).
48 * This will round your data coordinates to the nearest screen pixel before
50 * @param {number} x The data x-coordinate at which to sample.
51 * @param {number} y The data y-coordinate at which to sample.
52 * @return {Array.<number>} a 4D array: [R, G, B, alpha]. All four values
53 * are in [0, 255]. A pixel which has never been touched will be [0,0,0,0].
55 PixelSampler
.prototype.colorAtCoordinate
= function(x
, y
) {
56 var dom_xy
= this.dygraph_
.toDomCoords(x
, y
);
57 return this.colorAtPixel(Math
.round(dom_xy
[0]), Math
.round(dom_xy
[1]));
60 export default PixelSampler
;