Skip to content

Instantly share code, notes, and snippets.

@seejohnrun
Created December 17, 2013 21:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save seejohnrun/8013021 to your computer and use it in GitHub Desktop.
Save seejohnrun/8013021 to your computer and use it in GitHub Desktop.
Manipulate http://make8bitart.com/ using phantomjs (and a few canvas workarounds) to let the computer be the artist this example generates: http://i.minus.com/jccK6EuB7LRdl.png
var url = 'https://lh6.googleusercontent.com/-NQAMokukfdE/AAAAAAAAAAI/AAAAAAAAAAA/zSaLZajdgEI/s48-c-k-no/photo.jpg';
var xoffset = 240;
var yoffset = 210;
var pixelSize = 7;
var viewportWidth = 800;
var viewportHeight = 670;
//
// And away we go
//
var webpage = require('webpage');
var page = webpage.create();
page.viewportSize = { width: viewportWidth, height: viewportHeight };
page.settings.webSecurityEnabled = false;
page.open('http://make8bitart.com/', function (status) {
// set the size of the picker
var setSize = function (size) {
page.evaluate(function (s) {
$('#pixel-size').val(s).trigger('change');
}, size);
};
// set the color of the picker
var setColor = function (color) {
page.evaluate(function (c) {
$('#hex-color').val(c).focus();
}, color);
};
// How to draw a certain color at a certain location
var drawPixel = function (color, x, y) {
setColor(color);
page.sendEvent('click', x, y);
};
// Get pixels of an image using a browser canvas render
var getPixels = function (url, callback) {
page.onCallback = function (width, height, data) {
callback(width, height, data);
};
page.evaluate(function (url) {
var img = new Image;
img.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d')
context.drawImage(img, 0, 0, img.width, img.height);
var data = context.getImageData(0, 0, img.width, img.height).data;
window.callPhantom(img.width, img.height, data);
};
img.src = url;
}, url);
};
// convert a point to hex to avoid validation issues
var toHex = function toHex(n) {
return '0123456789ABCDEF'.charAt((n - n % 16) / 16) + '0123456789ABCDEF'.charAt(n % 16);
}
var convertPointToHex = function (data, o) { // ignore semi-transparency
return toHex(data[o]) + toHex(data[o + 1]) + toHex(data[o + 2]);
};
// draw what we're told to
getPixels(url, function (width, height, data) {
setSize(pixelSize);
var p, color;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
if (data[p + 3] === 0) { continue; } // ignore full transparency
p = ((y * width) + x) * 4;
color = convertPointToHex(data, p);
drawPixel(color, xoffset + x * pixelSize, yoffset + y * pixelSize);
}
}
// And then take a screenshot
page.render('out.png');
phantom.exit();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment