foxy-moxy/server.js

67 lines
1.9 KiB
JavaScript
Raw Normal View History

2016-12-16 18:05:14 +00:00
var fs = require('fs');
var express = require('express');
2016-12-17 02:54:21 +00:00
var uuid = require('uuid/v4');
2016-12-17 03:24:17 +00:00
var sanitize = require('sanitize-filename');
2016-12-16 18:05:14 +00:00
var Canvas = require('canvas');
2016-12-15 21:23:38 +00:00
var Fox = require('./js/fox.js');
2016-12-16 18:34:37 +00:00
var renderFox = require('./js/render-fox.js');
2016-12-15 19:24:22 +00:00
2016-12-17 02:54:21 +00:00
function composeImage(width, height, seed) {
var fox = Fox(width, height, seed);
var canvas = new Canvas(width, height);
var ctx = canvas.getContext('2d');
renderFox(canvas, fox);
return canvas;
};
function writeFoxToDisk (width, height, seed) {
if (seed === undefined) seed = uuid();
var canvas = composeImage(width, height, seed);
var fileName = "fox-" + seed + ".png";
var filePath = __dirname + '/images/' + fileName;
fs.writeFile(filePath, canvas.toBuffer(), function(err) {
if (err) console.log('error', err);
});
return fileName;
};
function writeFoxesToDisk (width, height, n=10) {
var fileNames = [];
for (var i = 0; i < n; i++) {
2016-12-17 02:54:21 +00:00
fileNames.push(writeFoxToDisk(width, height));
}
return fileNames;
};
2016-12-15 19:24:22 +00:00
var app = express();
2016-12-15 20:20:41 +00:00
app.use(express.static(__dirname + '/images'));
2016-12-15 19:24:22 +00:00
2016-12-15 21:23:38 +00:00
app.get('/', function(req, res) {
2016-12-17 02:54:21 +00:00
var fileNames = writeFoxesToDisk(200, 200, 28);
var images = fileNames.map(fileName => '<img src="/' + fileName + '"/>');
res.send(images.join(''));
2016-12-15 19:24:22 +00:00
});
2016-12-17 02:54:21 +00:00
app.get('/:width', function(req, res) {
var width = parseInt(req.params.width);
if (!width) width = 400;
var fileName = writeFoxToDisk(width, width);
res.send('<img src="/' + fileName + '"/>');
});
app.get('/:width/:seed', function(req, res) {
var width = parseInt(req.params.width);
2016-12-17 03:24:17 +00:00
var seed = sanitize(req.params.seed);
2016-12-17 02:54:21 +00:00
if (width === undefined) width = 400;
2016-12-17 03:24:17 +00:00
if (!seed) seed = uuid();
2016-12-17 02:54:21 +00:00
var fileName = writeFoxToDisk(width, width, seed);
res.send('<img src="/' + fileName + '"/>');
});
2016-12-15 19:24:22 +00:00
app.listen(process.env.PORT || 3000);
console.log('listening on http://localhost:3000');