Skip to content

Instantly share code, notes, and snippets.

@noxan
Created June 7, 2014 11:37
Show Gist options
  • Save noxan/9bcc641697e5a0fdbdb7 to your computer and use it in GitHub Desktop.
Save noxan/9bcc641697e5a0fdbdb7 to your computer and use it in GitHub Desktop.
Generate placeholder images (nice gradients) for express based node applications. Requires node-canvas.
var Canvas = require('canvas');
var randomInt = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var randomColor = function() {
var color = '#' + randomInt(0, 16777215).toString(16);
for(var i = 0; i < 7 - color.length; i++) {
color = color + '0';
}
return color;
}
exports.placeholder = function(req, res) {
var canvas = new Canvas(400, 400);
var ctx = canvas.getContext('2d');
var image = new Canvas.Image;
var offset = randomInt(0, 400);
var gradient = ctx.createLinearGradient(0, offset, 400, 400 - offset);
var stepCount = randomInt(1, 3);
for(var step = 0; step < stepCount ; step++) {
var color = randomColor();
gradient.addColorStop(step / (stepCount - 1), color);
}
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 400, 400);
res.setHeader('content-type', 'image/png');
canvas.createPNGStream().pipe(res);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment