-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
index.js
98 lines (81 loc) · 2.64 KB
/
index.js
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
var convert = require('color-convert');
if (process.argv) {
var Canvas = (require)('canvas');
}
function createCanvas (width, height) {
if (typeof Canvas !== 'undefined') {
return new Canvas(width, height);
}
else {
var canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
return canvas;
}
}
var exports = module.exports = function (canvas) {
var opts = {};
if (typeof canvas !== 'object') {
canvas = createCanvas(arguments[0], arguments[1]);
opts = arguments[2] || {};
}
else if (!canvas) {
canvas = createCanvas(500, 500);
}
else if (Object.getPrototypeOf(canvas) === Object.prototype) {
opts = canvas;
if (opts.canvas) {
canvas = opts.canvas;
}
else if (opts.width && opts.height) {
canvas = createCanvas(opts.width, opts.height);
}
}
return new Heat(canvas, opts)
};
exports.Heat = Heat;
function Heat (canvas, opts) {
if (!opts) opts = {};
this.canvas = canvas;
this.alphaCanvas = createCanvas(canvas.width, canvas.height);
this.radius = opts.radius || 20;
this.threshold = opts.threshold || 0;
}
Heat.prototype.addPoint = function (x, y, radius) {
var ctx = this.alphaCanvas.getContext('2d');
if (!radius) radius = this.radius;
var g = ctx.createRadialGradient(x, y, 0, x, y, radius);
var a = 1 / 10;
g.addColorStop(0, 'rgba(255,255,255,' + a + ')');
g.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = g;
ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
return this;
};
Heat.prototype.draw = function () {
var width = this.canvas.width;
var height = this.canvas.height;
var ctx = this.alphaCanvas.getContext('2d');
var values = ctx.getImageData(0, 0, width, height);
var heat = ctx.createImageData(width, height);
for (var i = 0; i < values.data.length; i += 4) {
var v = values.data[i+3];
if (v > this.threshold) {
var theta = (1 - values.data[i+3] / 255) * 270;
var rgb = convert.hsl2rgb(theta, 100, 50);
heat.data[i] = rgb[0];
heat.data[i+1] = rgb[1];
heat.data[i+2] = rgb[2];
heat.data[i+3] = v;
}
}
this.clearCanvas();
this.canvas.getContext('2d').putImageData(heat, 0, 0);
return this;
};
Heat.prototype.clearCanvas = function () {
var ctx = this.canvas.getContext('2d');
ctx.fillStyle = null;
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
return this;
};