-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
69 lines (65 loc) · 1.67 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
var vm = require("vm");
var Canvas = require("canvas");
var GifEncoder = require("gif-encoder");
var request = require("request");
var streams = require("memory-streams");
function getDweetCode() {
return new Promise(function(resolve, reject) {
request("https://www.dwitter.net/api/dweets/?limit=1", function(error, response, body) {
var code = JSON.parse(body).results.code
resolve(code);
});
});
}
function getFrames(cb) {
return new Promise(function(resolve, reject) {
getDweetCode().then(function(code) {
var framestouse = 50;
var can = new Canvas(1920, 1080);
var ctx = can.getContext("2d");
var frameArray = [];
var sandbox = {
S: Math.sin,
C: Math.cos,
T: Math.tan,
R: function(r, g, b, a) {
return "rgba(" + r + "," + g + "," + b + "," + a + ")";
},
c: can,
x: ctx,
t: 0
};
var script = new vm.Script(code);
var context = vm.createContext(sandbox);
var timesaround = 0;
var intervalId = setInterval(function() {
if (timesaround < framestouse) {
script.runInContext(context);
frameArray.push(ctx.getImageData(0, 0, can.width, can.height).data);
context.t += 100;
timesaround += 1;
} else {
clearInterval(intervalId);
resolve(frameArray);
}
}, 100);
});
});
}
function start() {
return new Promise(function(resolve, reject) {
getFrames().then(function(frames) {
var gif = new GifEncoder(1920, 1080);
var writer = new streams.WritableStream();
gif.pipe(writer);
gif.setDelay(100);
gif.setRepeat(0);
frames.forEach(function(frame) {
gif.addFrame(frame);
});
gif.finish();
resolve(writer.toBuffer());
});
});
}
module.exports = start;