Last active
October 3, 2015 20:37
-
-
Save crystalschang/2522608 to your computer and use it in GitHub Desktop.
Front-end canvas pixel analysis: Take an image url as an input, and render a pixelated version of the image on the canvas.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="http://soo-jung.com/lib/jquery.js"></script> | |
<script src="jquery.getimagedata.min.js"></script> | |
<script> | |
$.getImageData({ | |
url: 'https://www.hackerschool.com/assets/slideshow_01-540531c0d5690f948a4d5d02c5400827.jpg', | |
server: 'http://maxnov.com/getimagedata/getImageData.php', | |
success: function (image) { | |
// Set up the canvas | |
var can = document.getElementsByTagName('canvas')[0]; | |
var ctx = can.getContext('2d'); | |
// Set the canvas width and height to the same as the image | |
$(can).attr('width', image.width); | |
$(can).attr('height', image.height); | |
// Draw the image on to the canvas | |
ctx.drawImage(image, 0, 0, image.width, image.height); | |
// Setup the image data. The canvas will be a WIDTH_NUMS x HEIGHT_NUMS grid. | |
// Determine the size of each grid box | |
var WIDTH_NUMS = 30; | |
var HEIGHT_NUMS = 30; | |
var gridWidth = image.width/WIDTH_NUMS; | |
var gridHeight = image.height/HEIGHT_NUMS; | |
var startX = 0; | |
var startY = 0; | |
// For each grid box, determine the average color | |
for (var k = 0; k < WIDTH_NUMS; k++) { | |
for (var l = 0; l < HEIGHT_NUMS; l++) { | |
// Figure out the corner coordinates for this grid box | |
startX = (k*gridWidth); | |
startY = (l*gridHeight); | |
var image_data = ctx.getImageData(startX, startY, gridWidth, gridHeight); | |
var image_data_array = image_data.data; | |
// Determine average RGB | |
var r = 0; | |
var g = 0; | |
var b = 0; | |
for (var i = 0, j = image_data_array.length; i < j; i+=4) { | |
r += image_data_array[i]; | |
g += image_data_array[i+1]; | |
b += image_data_array[i+2]; | |
} | |
var box = {}; | |
var count = image_data_array.length/4; | |
box.r = r/count; | |
box.g = g/count; | |
box.b = b/count; | |
// Fill this grid's data array with the average rgb | |
for (var i = 0, j = image_data_array.length; i < j; i+=4) { | |
image_data_array[i] = box.r; | |
image_data_array[i+1] = box.g; | |
image_data_array[i+2] = box.b; | |
} | |
// Write the image data to the canvas | |
ctx.putImageData(image_data, startX, startY); | |
} | |
} | |
}, | |
error: function(xhr, text_status){ | |
console.log("fml! "+text_status); | |
} | |
}); | |
</script> | |
</head> | |
<body> | |
<canvas></canvas> | |
<div class="result"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment