aboutsummaryrefslogtreecommitdiffstats
path: root/web/js/nms-color-util.js
blob: d1336c351d6ef8548ff6d89fe945f9727065a57e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"use strict";
/*
 * Some stolen colors that look OK.
 *
 * PS: Stolen from boostrap, because we use bootstrap and these look good
 * and match.
 */

var nmsColor = nmsColor || {
  _cache: [],
  cyan: "#0dcaf0",
  blue: "#0d6efd",
  green: "#198754",
  teal: "#20c997",
  orange: "#fd7e14",
  red: "#dc3545",
  white: "#fff",
};

/*
 * Return a random-ish color (for testing)
 */
nmsColor.random = function () {
  var colors = [
    nmsColor.white,
    nmsColor.red,
    nmsColor.teal,
    nmsColor.orange,
    nmsColor.green,
    nmsColor.blue,
    nmsColor.cyan,
  ];
  var i = Math.round(Math.random() * (colors.length - 1));
  return colors[i];
};

/*
 * Set up the hidden gradient canvas, using an array as input.
 *
 * This gives us a flexible way to get gradients between any number of
 * colors (green to red, or blue to green to orange to red to white to pink
 * to black and so on).
 *
 * Typically called when setting up a map handler. Currently "single
 * tenant", since there's just one canvas.
 *
 * XXX: We have to store the gradients in nms.* and restore this when we
 * resize for the moment, because this canvas is also re-sized (which isn't
 * really necessary, but avoids special handling).
 */
nmsColor.drawGradient = function (gradients) {
  var ctx = nmsMap._c.hidden.ctx; // FIXME: Move it away...
  var gradient = ctx.createLinearGradient(0, 0, 1000, 0);
  var stops = gradients.length - 1;
  nmsColor._cache = [];
  nms.gradients = gradients;
  for (var color in gradients) {
    var i = color / stops;
    gradient.addColorStop(i, gradients[color]);
  }
  ctx.beginPath();
  ctx.strokeStyle = gradient;
  ctx.moveTo(0, 0);
  ctx.lineTo(1000, 0);
  ctx.lineWidth = 10;
  ctx.closePath();
  ctx.stroke();
  ctx.moveTo(0, 0);
};

/*
 * Get the color of a gradient, range is from 0 to 999 (inclusive).
 */
nmsColor.getColorStop = function (x) {
  x = parseInt(x);
  if (isNaN(x)) x = 0;
  if (x > 999) x = 999;
  if (x < 0) x = 0;
  return nmsColor._getColor(x, 0);
};

/*
 * Get the color on the hidden canvas at a specific point. Could easily be
 * made generic.
 */
nmsColor._getColor = function (x, y) {
  if (nmsColor._cache[x] != undefined) return nmsColor._cache[x];
  var ctx = nmsMap._c.hidden.ctx; // FIXME: Move it away...
  try {
    var imageData = ctx.getImageData(x, y, 1, 1);
  } catch (e) {
    console.log("x: " + x);
    console.log(e);
  }
  var data = imageData.data;
  if (data.length < 4) return false;
  nmsColor._cache[x] = "rgb(" + data[0] + "," + data[1] + "," + data[2] + ")";
  return nmsColor._cache[x];
};