Bug fix: indexFromSetName on invisible sets (#771)
[dygraphs.git] / auto_tests / tests / PixelSampler.js
... / ...
CommitLineData
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 */
14var 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 */
29PixelSampler.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 * 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].
41 */
42PixelSampler.prototype.rgbAtPixel = function(x, y) {
43 return this.colorAtPixel(x, y).slice(0, 3);
44};
45
46/**
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
49 * sampling.
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].
54 */
55PixelSampler.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]));
58};
59
60export default PixelSampler;